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.
Asked
Active
Viewed 7,114 times
2
-
Can't you give us an HTML markup???? What kind of text is it? how many "texts" do you have in the page? – gdoron Mar 25 '12 at 22:56
-
...*searched everywhere but can't find it* hmmm? – Caffeinated Mar 25 '12 at 22:57
-
here's an example hello, i am new So when I hover my mouse over "am", I would be able to retrieve "am" – user1291899 Mar 25 '12 at 23:00
2 Answers
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'
);
-
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