How to get a word under the cursor?

Assuming there is an event mousestopattached to the entire document, what is the best way to determine the exact word under the cursor (if there is any text) when the mouse stops moving?

I can get the base element (jQuery) from the event handler - $(document.elementFromPoint(e.clientX, e.clientY))- and then what next?

So far, my idea has been to replace all text nodes in the hit element with your copy, where each word is wrapped in a DOM element (until you know which one), and then call again $(document.elementFromPoint(e.clientX, e.clientY))to get an element containing only the word under with the mouse.
But this seems like a complicated plan, and I wonder if something simpler is missing from me.

+5
source share
2 answers

Well, no magic tricks so far, so here is a boring boring (and yet working) solution:

  $(document.body).mousemove(function(e){

    var onmousestop = function() {
      function getHitWord(hit_elem) {
        var hit_word = '';
        hit_elem = $(hit_elem);

        //text contents of hit element
        var text_nodes = hit_elem.contents().filter(function(){
          return this.nodeType == Node.TEXT_NODE && this.nodeValue.match(/[a-zA-Z]{2,}/)
        });

        //bunch of text under cursor? break it into words
        if (text_nodes.length > 0) {
          var original_content = hit_elem.clone();

          //wrap every word in every node in a dom element
          text_nodes.replaceWith(function(i) {
            return $(this).text().replace(/([a-zA-Z-]*)/g, "<word>$1</word>")
          });

          //get the exact word under cursor
          var hit_word_elem = document.elementFromPoint(e.clientX, e.clientY);

          if (hit_word_elem.nodeName != 'WORD') {
            console.log("missed!");
          }
          else  {
            hit_word = $(hit_word_elem).text();
            console.log("got it: "+hit_word);
          }

          hit_elem.replaceWith(original_content);
        }

        return hit_word;
      }

      var hit_word = getHitWord(document.elementFromPoint(e.clientX, e.clientY));
      ...
    }
  }

There are a few other subtleties (like “noise reduction,” preserving dom substitution (like choosing), etc.), but you get the idea.

Here you can learn how to set up the mousestop event.

EDIT:

Creating custom html elements might not be such a breakthrough in IE (who would have thought?). More details here .

+2
source

I don't have code for you, but maybe this might help a bit:

  • When the cursor is in standby mode, get the coordinates
  • Search for elements inside the page with the specified coordinate
  • Use something like var s = getElementById('ElementIDFoundinStepAbove').innerHTML;

, , .

</" > Edit:

S/O:

2444430

, .

:)

+1

All Articles