Skip to content Skip to sidebar Skip to footer

Javascript: Multiple Mouseout Events Triggered

I'm aware of the different event models in Javascript (the WC3 model versus the Microsoft model), as well as the difference between bubbling and capturing. However, after a few ho

Solution 1:

The mouseout event on the inner div ‘bubbles’ to the outer div. To detect that this has happened from the outer div, check the target property of the event:

<div id="outer">
    <div id="inner">x</div>
</div>
document.getElementById('outer').onmouseout= function(event) {
    // deal with IE nonsenseif (event===undefined) event= window.event;
    var target= 'target'inevent? event.target : event.srcElement;

    if (target!==this) return;
    ...
};

The usual problem with mouseout is you get it when the pointer moves “out” of the parent even if it's only moving “in” to the child. You can detect this case manually by looking up the ancestor list of the element the mouse is moving into:

var other= 'relatedTarget'inevent? event.relatedTarget : event.toElement;
    while ((other= other.parentNode).nodeType===1)
        if (other===this) return;

This is the mousein/mouseout model: it is only interested about which element is the mouse's immediate parent. What you more often want is the mouseenter/mouseleave model, which considers element trees as a whole, so you'd only get mouseleave when the pointer was leaving the element-or-its-descendants and not moving directly into the element-or-its-descendants.

Unfortunately mouseenter/mouseleave is currently an IE-only event pair. Hopefully other browsers will pick it up as it is expected to be part of DOM Level 3 Events.

Post a Comment for "Javascript: Multiple Mouseout Events Triggered"