Reputation: 11448
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?
Upvotes: 1
Views: 3599
Reputation: 6114
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>
Upvotes: 1
Reputation: 22926
use
.one()
Description: Attach a handler to an event for the elements. The handler is executed at most once per element.
Upvotes: 4
Reputation: 31033
you can use unbind
on mouseenter
$("#elementID").mouseenter(function(e){
$(this).unbind(mouseenter);
});
or one
$("#elementID").one("mouseenter",function(){
//do something
});
Upvotes: 2