Javascript: alert checking for mouseover and mouseout firing multiple times
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 functio开发者_如何学JAVAnality 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.
You are adding multiple mouseout
events to the element.
You will need to unbind the previous one, or allocate it normally and let focusTime
be scoped to both functions.
Repeated event bindings... Try the following code out.
<html>
<head></head>
<title>A test page</title>
<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", tellTime, false);
}
function tellTime(){
elm.removeEventListener("mouseout", tellTime, false);
var blurTime = new Date().getTime();
if ((blurTime - focusTime) > 2000) {
alert ('You spent a long time there');
}
}
}
</script>
<body>
<a href="www.google.co.in">This is a hyperlink</a>
<p> This is just some bloody text </p>
</body>
</html>
精彩评论