JavaScript mouseover/mouseout issue with child element

ali picture ali · May 16, 2012 · Viewed 28.7k times · Source

I have this little problem and I am requesting for your help. I have a div element, inside which I have an img element, like this

<div id="parent" onmouseover="MyFuncHover()" onmouseout="MyFuncOut()">
    <img id="child" src="button.png" style="visibility: hidden" />
</div>

<script type="text/javascript">
    function MyFuncHover() {
        // Here I have some code that makes the "child" visible
    }

    function MyFuncOut() {
        // Here I have some code that makes the "child" invisible again
    }
</script>

As you, see, the image is a child of the div. I want that only when I leave the div, the child to disappear. Yet, it looks like when I move the mouse over the image, the MyFuncOut() function is called (because, I suppose, I leave the div by hovering the image). I don't want that to happen. I want the MyFuncOut() function to be called only when I leave the div area.

I didn't know that when you move your mouse over a child control, it's parent calls the mouseout event (even if I am over the child, I am still over the parent, too). I am trapped into this and I need a little of your good advice. Thanks!

CHANGES

O.K. Event bubbling will not send the "mouseout" event to the parent when I "mouseout" the child. It also won't send the "mouseover" event to the parent when I "mouseover" the child. That's not what I need. I need the "mouseout" event of the parent to not be sent when I "mouseover" the child. Get it? Event bubbling is useful when I don't want, for example, a click event on the child to be propagated to the parent, but this is not my case. What is weird is that I have other elements inside the same parent that don't fire the "mouseout" event of the parent when I "mouseover" them.

Answer

Vishal Gowda picture Vishal Gowda · May 17, 2012

you can use "mouseenter" and "mouseleave" events available in jquery, here is the below code,

$(document).ready(function () {
        $("#parent").mouseenter(function () {
            $("#child").show();
        });
        $("#parent").mouseleave(function () {
            $("#child").hide();
        });
    });

above is to attach an event,

<div id="parent">
    <img id="child" src="button.png" style="display:none;" />
</div>