简体   繁体   中英

Javascript Mouseover bubbling from children

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...

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>

The hover method has two parameters, first for mouse in and second for mouse out.

$('your_div').hover(function(){
  // your code here.
}, function(){// any mouse out code here})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM