How to get a word under cursor using JavaScript? How to get a word under cursor using JavaScript? javascript javascript

How to get a word under cursor using JavaScript?


Further to the two other answers, you may be able to split your paragraphs up into spans using jQuery (or javascript generally).

That way, you wouldn't need to think about outputting your text with spans around the words. Let your javascript do it for you.

e.g.

<p>Each word will be wrapped in a span.</p><p>A second paragraph here.</p>Word: <span id="word"></span><script type="text/javascript">    $(function() {        // wrap words in spans        $('p').each(function() {            var $this = $(this);            $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));        });        // bind to each span        $('p span').hover(            function() { $('#word').text($(this).css('background-color','#ffff66').text()); },            function() { $('#word').text(''); $(this).css('background-color',''); }        );    });</script>

Note that the above code, while it works, will strip out any html inside your paragraph tags.

jsFiddle example


My other answer works only in Firefox. This answer works in Chrome. (Might work in Firefox, too, I don't know.)

function getWordAtPoint(elem, x, y) {  if(elem.nodeType == elem.TEXT_NODE) {    var range = elem.ownerDocument.createRange();    range.selectNodeContents(elem);    var currentPos = 0;    var endPos = range.endOffset;    while(currentPos+1 < endPos) {      range.setStart(elem, currentPos);      range.setEnd(elem, currentPos+1);      if(range.getBoundingClientRect().left <= x && range.getBoundingClientRect().right  >= x &&         range.getBoundingClientRect().top  <= y && range.getBoundingClientRect().bottom >= y) {        range.expand("word");        var ret = range.toString();        range.detach();        return(ret);      }      currentPos += 1;    }  } else {    for(var i = 0; i < elem.childNodes.length; i++) {      var range = elem.childNodes[i].ownerDocument.createRange();      range.selectNodeContents(elem.childNodes[i]);      if(range.getBoundingClientRect().left <= x && range.getBoundingClientRect().right  >= x &&         range.getBoundingClientRect().top  <= y && range.getBoundingClientRect().bottom >= y) {        range.detach();        return(getWordAtPoint(elem.childNodes[i], x, y));      } else {        range.detach();      }    }  }  return(null);}    

In your mousemove handler, call getWordAtPoint(e.target, e.x, e.y);


Preamble:

If you have multiple spans and nested HTML that separate words (or even characters in words), then all the above solutions will have trouble returning the full and correct word.

Here is an example from the bounty question: Х</span>rт0съ. How to properly return Хrт0съ? These issues were not addressed back in 2010, so I will present two solutions now (2015).


Solution 1 - Strip inner tags, wrap spans around each full word:

One solution is to strip out the span tags inside paragraphs but preserve their text. Split words and phrases are thus joined back together as regular text. Each word is found by whitespace division (not just a space), and those words are wrapped in spans which can be individually accessed.

In the demo, you can highlight the entire word and thus get the text of the whole word.


pic 0

Code:

$(function() {  // Get the HTML in #hoverText - just a wrapper for convenience  var $hoverText = $("#hoverText");  // Replace all spans inside paragraphs with their text  $("p span", $hoverText).each(function() {    var $this = $(this);    var text = $this.text(); // get span content    $this.replaceWith(text); // replace all span with just content  });  // Wrap words in spans AND preserve the whitespace  $("p", $hoverText).each(function() {    var $this = $(this);    var newText = $this.text().replace(/([\s])([^\s]+)/g, "$1<span>$2</span>");    newText = newText.replace(/^([^\s]+)/g, "<span>$1</span>");    $this.empty().append(newText);  });  // Demo - bind hover to each span  $('#hoverText span').hover(    function() { $(this).css('background-color', '#ffff66'); },    function() { $(this).css('background-color', ''); }  );});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div id="hoverText">  <p><span class="kinovar"><span id="selection_index3337" class="selection_index"></span>По f7-мъ часЁ твори1тъ сщ7eнникъ начaло съ кади1ломъ и3 со свэщeю, цrкимъ двeремъ tвeрзєннымъ, и3 поeтъ: Х</span>rт0съ воскRсе: <span class="kinovar">со стіхи2. И# по стісёхъ pал0мъ: Б</span>лгcви2 душE моS гDа: <span class="kinovar">И# є3ктеніA. Тaже каfjсма nбhчнаz.</span>  </p></div>