I'm writing a translate extension for firefox just similar like google translate extension. I achieve that the listening mauseup and mousedown events to get selection text and popup a div that you can click.

Due to i am new at javacript, i would like some feedback for above code. Can i do any improvement?

var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
var selection = "";
function getSelectionText() {
  var text = "";
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control"){
    text = document.selection.createRange().text;
  return text;
document.addEventListener("mousedown", checkSelectionText);
document.addEventListener("mouseup", checkSelectionText);

function checkSelectionText(event) {
  if (event.target == document.querySelector('.selection_bubble')) {

  setTimeout(function() {
    selection = getSelectionText();
    if (selection) {
      document.querySelector('.selection_bubble').style.top = (event.pageY+3) + "px";
      document.querySelector('.selection_bubble').style.left = (event.pageX+3) + "px";
      document.querySelector('.selection_bubble').style.visibility = 'visible';
    } else {
      document.querySelector('.selection_bubble').style.visibility = 'hidden';

document.querySelector('.selection_bubble').addEventListener("click", openPopup);

function openPopup(event) {
  chrome.runtime.sendMessage({action: 'openModal', selection: selection});
  document.querySelector('.selection_bubble').style.visibility = 'hidden';



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.