2

I searched everywhere but can't find it. So I'm asking it here. I want to get the text when the mouse is on top (hover) of that text inside an html page. I tried using getClientRect, but they only give me coordinates, and not text. Does anybody know how to do this with javascript or html? Thanks.

user1291899
  • 41
  • 1
  • 4

2 Answers2

2

If you've got access to jQuery, you can use the .mouseover() event handler. You can bind it to a specific DOM element and then grab the value either through val, or innerhtml.

d_ethier
  • 3,873
  • 24
  • 31
  • But the innerhtml brings back all the text, I just need the text that the mouse is over. – user1291899 Mar 25 '12 at 22:59
  • Not sure there is a way to do that other than wrapping each word (or sentence -- depending on your circumstances) in a span element with a class event handler attached to it. -- Just noticed James Hay's response. Much better! – d_ethier Mar 26 '12 at 01:02
2

It depends on what element you're trying to get the text for, but possibly what you want to do is use the mouseenter event.

$(parentselector).on({
    'mouseenter': function(){
            alert($(this).html()); // .html() or .val() depending on the element
        }
    },
    targetselector
);

EDIT:

How to get a word under cursor using JavaScript?

Create your HTML like this

<html>
   <head></head>
   <body>
      <span class="word">Hello</span>
      <span class="word">I</span>
      <span class="word">am</span>
      <span class="word">new</span>
   </body>
</html>

Then something like this in jQuery.

$('body').on({
    'mouseenter': function(){
            var txt = $(this).html();
        }
    },
    'span.word'
);
Community
  • 1
  • 1
James Hay
  • 7,115
  • 6
  • 33
  • 57
  • Hi, thanks for the response, but doesn't that bring back all the text inside an element? I just want one word inside the array of text nodes. – user1291899 Mar 25 '12 at 23:03