mouseover/mouseout v.s. mousenter/mouseleave events in JavaScript and JQuery

The typical event example, and the one used by this lynda.com JQuery tutorial, is the yellow div that highlights red when you roll your mouse over it.

<script type="text/javascript">
   jQuery(function() {
     jQuery("#example1").bind("mouseenter", highlight);
     jQuery("#example1").bind("mouseleave", highlight);
  });
  function highlight(evt) {
         jQuery(this).toggleClass("highlight");
     }
</script>

When I initially wrote a second example (see below) where the div being highlighted contains an inner div, I experienced some odd behavior. The div would highlight, but then de-highlight when the mouse moved over the child div. You can see in the code below, that I was mixing mouseover (normally paired with mouseout) and mouseleave (normally paired with mouseenter).

<script type="text/javascript">
   jQuery(function() {
     jQuery("#example2").bind("mouseover", highlight);
     jQuery("#example2").bind("mouseleave", highlight);   
  });
  function highlight(evt) {
         jQuery(this).toggleClass("highlight");
     }
</script>

A blog post by Kurniawan explained this behavior:

Mouseover fires when the pointer moves into or out from child element, while mouseenter does’t.”

Here is perhaps a clearer example: Instead of toggling highlighting, the events are printing to the screen. You see that the events fire when the mouse enters and leaves the child div, even though we have only bound the events to the parent:

<script type="text/javascript">
   jQuery(function() {
     jQuery("#example3").bind("mouseover", printEvent);
     jQuery("#example3").bind("mouseout", printEvent);
  });
    function printEvent(evt) {
        jQuery("#events").append(evt.type + " ");
    }
</script>

This entry was posted in Software Development and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">