I have a simple html page, with many links.
When a link is hovered over, it calls a function dothis()
that changes the contents of a div on the page, but I only want it to run the function once for each link no matter how many times it is hovered over.
For example, if the user hovers over a particular link, moves the mouse away and hovers again, it will not load the function again (each link has this 1 hover limit, so the user could hover over link A, then link B can still run the function when hovered over (but only once for each link)).
I have jquery loaded if that makes things easier.
Any ideas how I can do this?
I have a simple html page, with many links.
When a link is hovered over, it calls a function dothis()
that changes the contents of a div on the page, but I only want it to run the function once for each link no matter how many times it is hovered over.
For example, if the user hovers over a particular link, moves the mouse away and hovers again, it will not load the function again (each link has this 1 hover limit, so the user could hover over link A, then link B can still run the function when hovered over (but only once for each link)).
I have jquery loaded if that makes things easier.
Any ideas how I can do this?
Share Improve this question asked Dec 31, 2011 at 19:49 David19801David19801 11.4k26 gold badges86 silver badges127 bronze badges 1- possible duplicate of Only fire an event once? --- Happy New Year! – Felix Kling Commented Dec 31, 2011 at 19:54
3 Answers
Reset to default 4use
.one()
jQuery API.
Description: Attach a handler to an event for the elements. The handler is executed at most once per element.
you can use unbind
on mouseenter
$("#elementID").mouseenter(function(e){
$(this).unbind(mouseenter);
});
or one
$("#elementID").one("mouseenter",function(){
//do something
});
Here's how I'd do it:
When a user hovers over a link, a function will check an internal variable. If it's null, the function will set the internal variable so that it doesn't call the dothis() function more than once.
<!DOCTYPE html>
<html>
<head>
<title>Hover Once</title>
</head>
<body>
<a href="#" onmouseover="onHover(this)">Link 1</a>
<a href="#" onmouseover="onHover(this)">Link 2</a>
<a href="#" onmouseover="onHover(this)">Link 3</a>
<script>
function onHover(element) {
if(element.alreadyHovered == null) {
console.log("call dothis()");
element.alreadyHovered = true;
}
}
</script>
</body>
</html>