Question

Hi: when I add a mouseout event to a parent element,it seems that all of its child are added this event also,it works well if the event is a mouse click and etc.

However for the mouseout event,this will cause some unexpected result.

Take a look at this example:

<html>
    <head>
        <script type="text/javascript">
            function init(){
                document.getElementById('par').onmouseout=function(){alert('mouse out')};
            }
    </script>
    </head>
    <body onload='init()'>
        <div id="par" style="width:400px;height:300px">
            <div style="background-color:red;width:100%;height:150px"></div>
            <div style="background-color:black;width:100%;height:150px"></div>
        </div>
    </body>
</html>

please Move from the red div to the black div,then move out of the black div,then you will get two alert window,I just want one.

So how to fix it?

Was it helpful?

Solution

That's not possible using plain javascript without the mouseleave event, which, to my knowledge, is only supported by Internet Explorer.

Javascript toolkits may provide a solution, jQuery for instance emulates that event:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top