1
votes

For example, if I have:

<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur urna felis, convallis quis, placerat in, elementum quis, libero. Nam quis lacus. Vivamus rhoncus quam et metus. Praesent et velit eget sem vestibulum volutpat. Integer sed risus. Integer quis libero id diam bibendum luctus. Donec eleifend. Curabitur ut sem. Praesent at est ac sem rhoncus interdum. Etiam arcu nulla, molestie dictum, mollis sed, imperdiet sit amet, neque. Fusce at nibh sit amet mi eleifend aliquam. Nunc tristique scelerisque risus. Praesent et velit id magna volutpat volutpat.</div>

...and then it's loaded in the browser and I'm hovering my mouse over various words, is there any reasonable way to detect which word is being hovered over? Any unreasonable way?

4

4 Answers

3
votes

This has to be heavy, but it works ( jQuery ) :

// highlight every word found in a <p>
$("p").each(
    function () { 
        var content = "";    
        var words = $(this).html().match(/\W*\w+/g) ;
        var in_tag = false ;
        for (i in words) {
            if (words[i].match(/^\W*</)) {
                in_tag = true ;
            }
            if (words[i].match(/^\W*>/)) {
                in_tag = false ;
            }
            if (in_tag) {
                content += words[i];
            } else {
                content += words[i].replace(/(\w+)/,'<span class="word">$1</span>');
            }
        }
        $(this).html(content);
    }
);

// example event

$(".word").mouseover(function() { $(this).css("background-color","#FF0") });
$(".word").mouseout(function() { $(this).css("background-color","") });

You may want to replace $("p") with $("#mydiv").

EDIT : I wrote that there is a bug breaking tags, but tags are not the problem here ; the problem is that this code does not cope with HTML entities. In the current page, for example, when processing &lt;div&gt;, "gt" and "lt" are transformed like they were words by themselves, which is indeed wrong. Regexps would have to be a little more complicated to fix that bug.

2
votes

The unreasonable way involves calculating from the x,y coordinates of the mouse and then counting in an internal map of the paragraph. This will of course break when the next user uses a different font/size.

Look up those annoying intellitag ad popups that come when you rollover a keyword. You will notice that they are added after the page has loaded by a javascript that reads across every word and replaces important ones with surrounded spans.

0
votes

I don't think it's possible. You'd have to surround each word in some kind of identifiable tag like a span.

0
votes

I have no idea if this helps or not since I haven't looked at the code, I would check the NY times. I say this because I believe they have the site set up so you can double click on any word and get the definition. This might be a place to start.