Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery mouseover function firing multiple times

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>
like image 336
valoukh Avatar asked Jun 11 '14 13:06

valoukh


People also ask

What is the opposite of mouseover?

The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves.

How to handle hover in JavaScript?

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.

What is difference between Mouseenter () and mouseover () event?

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.


2 Answers

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/

like image 172
ivanjonas Avatar answered Sep 27 '22 23:09

ivanjonas


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?

like image 25
mpcabd Avatar answered Sep 27 '22 23:09

mpcabd