I have been using this method for a long time to set events for entire classes (for buttons etc):
$("div.bigButton").mouseover(function() { this.style.backgroundColor = '#dfdfdf'; });
However while doing some testing I have just noticed that when moving the mouse over these objects, the function fires 3 times! This is unnoticable when changing something like backgroundColor, but if I add an alert it's very obvious.
Any ideas what I'm doing wrong? I am concerned this may have an impact on performance later on.
Thanks
EDIT: Sorry, missing "style" off was a typo
The HTML is:
<div class="bigButton">
Test</div>
The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves.
jQuery hover() Method The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.
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 onmousemove event triggers every time the mouse pointer is moved over the div element.
This may be occurring because of nesting in your HTML elements. The jQuery documentation has a perfect example of this at the bottom of the page (don't confuse mouseover
and mouseenter
), as well as an example that prevents that unwanted behavior. http://api.jquery.com/mouseover/
If it's a hover effect you should use .hover
or .mouseenter
and .mouseleave
.
Also check for events bubbling from child elements that might be your problem.
Update
By trying this fiddle I can't seem to reproduce your problem, so your problem lies in your HTML/JavaScript code. Maybe you're attaching the handle three times?
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