Search code examples
javascripthtmljqueryjquery-eventsonmouseout

JavaScript's onmouseout event not working as expected


I'm having a problem with the onmouseout event when used in a dynamically created HTML element.

This is the HTML code:

<div id="imageWrapper">
    <img src="imageUrl" alt="">
</div>

This is -part of- the JavaScript code (using jQuery 1.7.2):

$('body').on('mouseout', 'div#imageWrapper', function () {
    alert("Test");
});

Clearly, what I want is to detect when the mouse leaves the div#imageWrapper and display an alert message.

And it works, but not as I expected it to work:

When the mouse leaves the div#imageWrapper it does displays the alert, but when inside the div the mouse goes over the img element, it displays it too (as if the img element was "an outside part of" the div). The weird thing is that when the mouse leaves the image (but the mouse remains on the div), it too displays the alert message.

Bottom line: JavaScript is treating both the div#imageWrapper and the img element inside it as two distinct div#imageWrappers.

Does anyone know how to fix this?


Solution

  • Use mouseenter and mouseleave instead:

    $('body').on('mouseleave', 'div#imageWrapper', function () {
        alert("Test");
    });