Javascript: How to detect if a word is highlighted

Solution 1:

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;

Solution 2:

Here is a script:

<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;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<form name="aform">
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>

Courtesy of Code Toad:

http://www.codetoad.com/javascript_get_selected_text.asp

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.

Solution 3:

In my case I wanted to be able to either highlight a text in a row of the and click in the row and send me to other route like "/entity/:id";

I created one function that detects the mouse is highlighting some text:

export const isHighlighting = () => {
  // detects mouse is highlighting a text
  return window.getSelection && window.getSelection().type === 'Range';
};

then I added this to the row of the

const handleClick = (id) => {
  if (!isHighlighting() {
     history.push(`/entity/${id}`)
  }
}

{data.map((item) => (
  <tr>
    <td onClick={() => handleClick(item.id)}>{item.name}</>
  </tr>
))}

in this way the user can hightlight then name field or click somewhere else and goes to "/entity/:id"