Code has been added to clipboard!

Master Query .mouseleave(): Bind Event Handlers to mouseleave Event

Reading time 1 min
Published Jan 9, 2018
Updated Oct 10, 2019

jQuery mouseleave: Main Tips

  • The jQuery .mouseleave() method attaches an event handler to mouseleave event, or triggers the assigned event handler.
  • This method is similar to .mouseout(). The main difference is that .mouseleave() does not react to event bubbling.
Theory is great, but we recommend digging deeper!

Usage of .mouseleave() Method

The .mouseleave()e in jQuery adds an event handler, running a function when the mouseleave event occurs. The method can also execute the assigned event handler.

Example
$("div").mouseleave(() => {
    $("div").css("background-color", "red");
});

Follow this syntax to trigger the mouseleave event:

$("selector").mouseleave();

Add the event handler by adding a function:

$("selector").mouseleave(event,function);

.mouseleave() and Event Bubbling

The event handler of mouseleave event is only triggered when the mouse exits the element it is attached to - not its descedant. That means jQuery .mouseleave() does not support event bubbling. See the example below to see the difference it creates between .mouseleave() and .mouseout():

Example
var i = 0;
$( "div.overout" )
  .mouseover(function() {
    $( "p:first", this ).text( "mouse over" );
    $( "p:last", this ).text( ++i );
  })
  .mouseout(function() {
    $( "p:first", this ).text( "mouse out" );
  });
 
var n = 0;
$( "div.enterleave" )
  .mouseenter(function() {
    $( "p:first", this ).text( "mouse enter" );
    $( "p:last", this ).text( ++n );
  })
  .mouseleave(function() {
    $( "p:first", this ).text( "mouse leave" );
  });