Problems with jQuery mouseover / mouseout events

The problem:

When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s mouseover and/or mouseout event.

The solution:

The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.

The reason:

This solution works because mouseover and mouseout events do not bubble from child to parent element.

thanks http://jquery-howto.blogspot.com/2009/04/problems-with-jquery-mouseover-mouseout.html

Code

<html>
    <head>
    <title>Bind Multiple Event Handlers</title>
        <style type="text/css">
        .divOne{
            height:40px;
            width:100px;
            background-color:#808080;
        }
        </style>
        <script language="javascript" type="text/javascript"
       src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
        </script>
        <script language="javascript" type="text/javascript">
            $(function() {
                $('.divOne').bind({
                    mouseenter: function() {
                        $(this).css("background-color", "#f0f0f0");
                    },
                    mouseout: function() {
                        $(this).css("background-color", "#808080");
                    },
                    click: function() {
                        alert("Div was clicked");
                    }
                });
            });             
        </script>   
    </head>
    <body>
    <form>
       <div class="divOne">
       </div>
     </form>
    </body>
</html>

Leave a comment