I'm working on a tooltip-esque application for a webpage, and want a Javascript event to be fired each time a user moves over a word.
Currently I have it working by putting a <span>
tag around each word individually, e.g. <span id="word1">word1</span> <span id="word2">word2</span> <span id="word3">word3</span>
and then handling the mouseover/out events for each.
This works OK, but sometimes the input text is thousands of words and all these tags seem to slow the browser (well slow down IE, at least). I use event delegation so there's not thousands of event handlers attached, and it's fast enough once rendered. The problem is the 8+ seconds it can take in the first place to render the individually tagged words when I set it via innerHTML, freezing the browser in the process.
(Edit: Just to clarify what I mean - the user enters a string of text, it's sent to the server by ajax and the HTML tags are added server-side. In the ajax success callback, I set the new HTML by setting the element's innerHTML directly. The delay is all on the the innerHTML setting, not server-side.)
Is there anyway that could be changed to just <span id="line1">word1 word2 word3</span>
and still work ? Is there any way of knowing which specific word the user mouseovered without putting an individual tag round each one ?
After coming across this page it turns out this is possible, at least to some extent. The below solution works only in IE, but that's really all I need as the other browsers were sufficiently fast with the individual tags solution anyway.
<script>
function getWordFromEvent (evt)
{
if (document.body && document.body.createTextRange)
{
var range = document.body.createTextRange();
range.moveToPoint(evt.clientX, evt.clientY);
range.expand('word');
document.getElementById("wordMouseIsOver").innerHTML = range.text;
}
}
</script>
<span onMouseMove="getWordFromEvent(event)">word1 word2 word3</span>
<BR>
<span id="wordMouseIsOver"> </span>
use Document Fragment's before you inject the long HTML into your document.
Read John Resig's (creater of the jQuery library) lengthy article on the benefit of using document fragments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With