Javascript: How to detect if a word is highlighted

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 (when you're reading an article and you highlight a word, the reference icon pops up). However the script is super complex. I'm 16 and not much of a programmer, so that is definitely way out of my league.



Here is a script:

function getSelText()
    var txt = '';
    if (window.getSelection)
        txt = window.getSelection();
    else if (document.getSelection)
        txt = document.getSelection();
    else if (document.selection)
        txt = document.selection.createRange().text;
    else return;
document.aform.selectedtext.value = txt;
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<form name="aform">
<textarea name="selectedtext" rows="5" cols="20"></textarea>

Courtesy of Code Toad:

In your case, you would want to call this script when the selection is made, and then you can process it however you wish, with an AJAX request to get relevant information for example, like NYtimes probably does.


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.


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;

Using rangy.js and jQuery:

$('#elem').on('keyup mouseup', function(){
    var sel = rangy.getSelection()
    if (sel.rangeCount === 0 || sel.isCollapsed) return


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.