Search code examples
jqueryimageonmouseover

Unexpected "onmouseover" behavior with jQuery


I have a "onmouse over" even binded to all elements of the page. When the mouse is over an element, it draws a red border to the closest upper relevant element (try aardvark for an example).

I have the follwing code :

<p>
<img height="333" width="250" title="Image par hyperbolic pants explosion sous licence CC - http://www.flickr.com/photos/74502564@N00/2716444681/" class="illustred" src="context-selector-test_files/rha_20090929_antivirus.jpg" />
Ah là là... ces abrutis qui continuent à refuser d'installer des antivirus parce que "
<em>
Je ne télécharge pas !
</em>
" ou "
<em>
Je ne vais que sur des sites de confiance.
</em>
</p>

You can see that the "img" is inside the "P".

The expected behavior is that when I go over "P", it get bordered, then when I go to the "IMG", the border go to the "IMG".

It doesn't.

The problem is not CSS because I don't use CSS, but 4 divs to simulate 4 borders in position "absolute" around an element. This is a mandatory for what comes next.

The problem occurs when I go over the "IMG", "mouseover" is indeed triggered, but immidiatly after, "mouse over" is triggered again on "P". I would understand "P -> IMG" but "IMG -> P" bugs me. And why, 2 mouseover in one row? I didn't move the mouse.

Now, what I am missing?

Specs :

  • html 4;
  • css 2;
  • jquery 1.3;
  • firefox 3.5;
  • ubuntu 9.04;
  • coffee 1.50 (l).

Solution

  • Stop event propagtion in your mouseover handler.

    $('selector').mouseover( function(e) {
        ...
        e.stopPropagation();
    });
    

    You also might want to think about using the hover() method or the hoverIntent() plugin. The latter will help to reduce any flashing as you simply drag your mouse across the page by enforcing a timed wait before the event handler is invoked.