Search code examples
javascripteventsmouseoverchildrenmouseleave

Javascript MouseOver / MouseOut children events


I have an element with some child elements. When the mouse leaves the parent element I want to hide the parent and it's children. Problem I'm having is that when I hover over any of the children, the mouseout event is being fired. What's the best way to prevent this? I really only want the event to fire when the mouse is not within the parent or any of it's children.


Solution

  • The event is bubbling up from the child to the parent (where it is being caught)

    You should catch the event on the children by adding a listener and making the propagation stop there.

    This code will stop the event from bubbling up to the parents handler

    function onMouseLeave(e)
    {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    }
    

    question: The mouse off event is fired by the parent, when it should not. Mouseing over the child should not trigger a mouse off from the parent. How can we stop this?