Javascript: How to detect if a word is highlighted

user369246 picture user369246 · Jan 17, 2011 · Viewed 36.4k times · Source

I'm writing a Firefox addon that is triggered whenever a word is highlighted. However I need a script that detects when a word is highlighted, and I'm stuck. An example would be nytimes.com (when you're reading an article and you highlight a word, the reference icon pops up). However the nytimes.com script is super complex. I'm 16 and not much of a programmer, so that is definitely way out of my league.

Answer

Tim Down picture Tim Down · Jan 17, 2011

The easiest way to do this is to detect mouseup and keyup events on the document and check whether any text is selected. The following will work in all major browsers.

Example: http://www.jsfiddle.net/timdown/SW54T/

function getSelectedText() {
    var text = "";
    if (typeof window.getSelection != "undefined") {
        text = window.getSelection().toString();
    } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}

function doSomethingWithSelectedText() {
    var selectedText = getSelectedText();
    if (selectedText) {
        alert("Got selected text " + selectedText);
    }
}

document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;