Pregunta

When I attach a mouseout event to a UL element, event do propagate to LI children despite I add stopPropagation()? What's wrong with my code?

http://jsfiddle.net/ubugnu/D7jwq/270/

HTML code:

<ul id="myul">
    <li>Outer
        <ul>
            <li>Inner
                <ul>
                    <li>Inner Inner</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>
<span id="count">0</span>

JS code:

document.getElementById('myul').addEventListener('mouseout', function(e){
    e.stopPropagation();
    document.getElementById('count').innerHTML = parseInt(document.getElementById('count').innerHTML) + 1;
}, false);

CSS code:

li { padding: 20px; border: solid 1px #ddd; }
¿Fue útil?

Solución

In this case, use 'mouseleave' instead of 'mouseout'. Quoting the doc:

The mouseleave event is fired when a pointing device (usually a mouse) is moved off the element that has the listener attached.

The mouseout event is fired when a pointing device (usually a mouse) is moved off the element that has the listener attached or off one of its children.

Note that mouseleave support has been added to Blink (Chrome/Opera 15) quite recently, that's why it's not available in Chrome 29 (but is already there in dev Chrome).

Otros consejos

Although mouseleave as @raina77ow said is the correct way to do this, if you are looking for wider browser compatibility, adding this code should work:

var ds=document.getElementById('myul').getElementsByTagName('*');
for(var l=0;l<ds.length;l++){
    ds[l].addEventListener('mouseout',function(e){e.stopPropagation()},true);
}

it is untested

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top