🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

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.
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

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" );
  });