Why does onmouseover run multiple times while I hover over one element?
I'm trying to run a simple animation when the user hovers over an icon but it runs multiple times.
I'm testing it here:
http://lujanventas.com/test.php
Anyway, any ideas on how to fix it? maybe using a listener instead?
This is the javascript running onmouseover:
function upIcon(n) {
console.log("Mouseover icon: " + n);
$('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 );
$('#icon' + n).animate({ backgroundPositionY : "+=15px" }, 200 );
}
The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element.
The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves. These events are special, because they have property relatedTarget . This property complements target . When a mouse leaves one element for another, one of them becomes target , and the other one – relatedTarget .
The onmouseover attribute fires when the mouse pointer moves over an element. Tip: The onmouseover attribute is often used together with the onmouseout attribute.
Try using mouseenter
and mouseleave
instead of mouseover
and mouseout
. The former fires only when the cursor enters the region of the element and the latter fires when the cursor moves between descendants as well.
I added this code to your page via my console and it worked as expected:
//bind an event handler to each nav element for the mouseenter event
$('.categoryButtons').children().bind('mouseenter', function () {
//call the `upIcon` function with the index of the current element
upIcon(($(this).index() + 1));
});
I also removed the inline onmouseover
code for each nav item.
You can use your existing function a bit differently and not use the anonymous function for your event handler (notice the function chaining to avoid duplicate selections):
function upIcon(event) {
var n = ($(this).index() + 1);
$('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 ).animate({ backgroundPositionY : "+=15px" }, 200 );
}
$('.categoryButtons').children().bind('mouseenter', upIcon);
When you reference an existing function as the event handler, it gets passed the event
object like any other event handler and you can also use this
to refer to the element on which the event was triggered.
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