Writing a code that does the following:
- Adds a mouse listener to a web-page on load
- Checks what element the mouse is positioned over
- If the mouse is positioned over an anchor tag then execute a certain functionality if it stays there for a certain period of time before leaving. For now am just arbitrarily using 10000 ms
Below is a sample code that I’m using as a testbed
<html>
<head></head>
<title>A test page</title>
<body>
<script type='text/javascript'>
document.addEventListener("mouseover", checkElement, false);
function checkElement(ev){
var elm = ev.target || ev.srcElement;
if(elm.tagName === 'A'){
var focusTime = new Date().getTime();
elm.addEventListener("mouseout", function() {tellTime(focusTime)}, false);
}
}
function tellTime(focusTime){
var blurTime = new Date().getTime();
if ((blurTime - focusTime) > 10000) {
alert ('You spent a long time there');
}
}
</script>
<a href="www.google.co.in">This is a hyperlink</a>
<p> This is just some bloody text </p>
</body>
</html>
When testing what I have found is that when the alert is fired it gets fired multiple times; twice, thrice or even more. I wanted to know why this could be happening and what I can do to avoid firing the alert multiple times for the same element.
Repeated event bindings… Try the following code out.