Javascript Mouseover bubbling from children

NDM picture NDM · Mar 15, 2010 · Viewed 7.3k times · Source

Ive got the following html setup:

<div id="div1">
<div id="content1">blaat</div>
<div id="content1">blaat2</div>
</div>

it is styled so you can NOT hover div1 without hovering one of the other 2 divs. Now i've got a mouseout on div1.
The problem is that my div1.mouseout gets triggered when i move from content1 to content2, because their mouseouts are bubbling.
and the event's target, currentTarget or relatedTarget properties are never div1, since it is never hovered directly...
I've been searching mad for this, but I can only find articles and solutions for problems who are the reverse of what I need. It seems trivial but I can't get it to work...
The mouseout of div1 should ONLY get triggered when the mouse leaves div1.

One of the possibilities would be to set some data on mouse enter and mouseleave, but I'm convinced this should work out of the box, since it is just a mouseout...

EDIT:

bar.mouseleave(function(e) {
                if ($(e.currentTarget).attr('id') == bar.attr('id')) {
                    bar.css('top', '-'+contentOuterHeight+'px');
                    $('#floatable-bar #floatable-bar-tabs span').removeClass('active');
                }
            });

changed the mouseout to mouseleave and the code worked...

Answer

Nick Craver picture Nick Craver · Mar 15, 2010

Use the mouseleave event instead or mouseout for this, it handles your specific issue. See here for details

From the docs on the difference:

The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

Example markup:

<div id="outer">
  Outer
  <div id="inner">
    Inner
  </div>
</div>