7

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>
valoukh
  • 541
  • 1
  • 8
  • 19

3 Answers3

8

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/

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
ivanjonas
  • 599
  • 7
  • 19
4

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?

ivanjonas
  • 599
  • 7
  • 19
mpcabd
  • 1,813
  • 15
  • 20
  • Thanks for your reply. I have tried mouseenter and it does the same. It also does it on a basic DIV with no child elements, so I think the issue may be elsewhere! – valoukh Jun 11 '14 at 13:22
  • I've tried your code in a [fiddle](http://jsfiddle.net/CAL8u/) and it didn't reproduce the issue, I updated my answer. – mpcabd Jun 11 '14 at 13:46
  • Same result here - please see my answer below :) – valoukh Jun 11 '14 at 14:24
3

I have discovered that the function that sets up the buttons was being run multiple times (each time the page content was delivered via ajax). I would have thought this would overwrite the 'mouseover' function, but it seems it was adding to it instead!

Thanks for all your help

valoukh
  • 541
  • 1
  • 8
  • 19