jQuery: the difference between mouseout and mouseleave

submit to reddit

The simple difference is that in the case with mouseout there is not event bubbling by default, while in mouseleave the events bubble.

Let’s make a short example.

When you point the cursor of the mouse over the red area where the div is and there is an attached event listener for mouseout of that div, something like divElement.onmouseout = doSomething;, where this is of course pseudo code, and when you point the mouse over the <a> tag yet again the mouseout of the div doesn’t fire. That’s because of the event bubbling in JavaScript where if one element receives the event, in this case the a tag has the mouse over it, the event bubbles to the parent element and than to the parent of the parent and so forth to the document root.

$.mouseout doesn’t bubbles the event

In JQuery the mouseout doesn’t bubbles and there comes the problem with the schema from the image. If you’ve:

$('div').mouseout();

and you point to the <a> tag even it is inside the div, the mouseout event fires. Now this seems strange. Your mouse is over that element but jQuery says you that it is out!

The solution is to replace the mouseout with mouseleave

This is easy and mouseleave helps you enter with the mouse over the <a> tag and still the mouseleave event doesn’t fire. But if you move the mouse outside the div and you point the body, now this seems normal.

Related posts:

  1. Event driven programming with jQuery – (part 3). What is a module?
  2. jQuery live() vs bind() performance
  3. Toggle the visibility with jQuery

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in javascript, micro tutorial and tagged , , . Bookmark the permalink.

3 Responses to jQuery: the difference between mouseout and mouseleave

  1. Drew Spencer says:

    Very useful, thanks a lot.

  2. Ben says:

    Learning jquery and really appreciate your simple and straightforward explanation. TY

  3. Re says:

    Hi man
    Thank you very much for your help (:

Leave a Reply

Your email address will not be published. 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="" highlight="">