1

I can't find a way to detect the text that a user is mousing over. The onmouseover event doesn't seem to support this feature. Is there a way to do this?

https://www.w3schools.com/jsref/event_onmouseover.asp

For example, if a user mouses over "example" from this paragraph, I'd like to be able to detect that they were mousing over "example", not just that they were mousing over the paragraph element.

EDIT: I think I was too ambiguous in what I needed. Basically what I'm trying to implement is a popup dictionary for dynamic text. When the user mouses over a word it might be part of a compound word, so I'd like to have not only the word but also its place in the paragraph so I can check if it's a compound word. It sounds like I should pre-process the HTML with spans around each word/compound word.

Lucas Xu
  • 11
  • 3
  • Possibly answered in this question. Seems each word in a span is the best way: http://stackoverflow.com/questions/7563169/detect-which-word-has-been-clicked-on-within-a-text – iCode Apr 05 '17 at 01:03

2 Answers2

1

I think that there'snt another way, you need to wrapper all words in differents html tags, for example a "span". You can do this with code below:

// 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',''); }
);
Douglas Gabriel
  • 131
  • 1
  • 8
0

You just wrap it inside span like this example:

<p>
Words Words Words Words Words <span onmouseover="alert('Mousing over A nice word!');">A Nice Word</span> Words Words Words Words 
</p>

https://jsfiddle.net/a4q6gqs2/

Konstantinos
  • 943
  • 1
  • 9
  • 20
  • 1
    This works, but it's a little cumbersome since I want to use this with dynamic data, and I'd have to add an event listener to every word. I was hoping there was a way I could do this without doing that, and it's further complicated in that I'd like to have information about the context its in, so for my example I'd like to both know that the user is hovering over "example" in the paragraph, and I also want to know the paragraph it's in and its position in that paragraph. – Lucas Xu Apr 05 '17 at 01:00
  • give us the code (or part of it) that you do the dynamic data maybe there is another way – Konstantinos Apr 05 '17 at 01:02