jQuery mouseleave()

The jQuery mouseleave() method is used to attach a function to run when a mouseleave event occurs i.e., when the mouse cursor leaves the selected element.

Syntax:

To trigger the mouseleave event for selected elements.

$(selector).mouseleave()

To add a function to the mouseleave event.

$(selector).mouseleave(function)

Function:

  • It is an optional parameter.
  • The function parameter specifies the function to run when the event occurs.

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#h1").mouseleave(function(){
$( "div" ).text( "Mouse is leaving heading" ).show().fadeOut( 2000 );
});
});
</script>
</head>
<body>
<h1 id="h1">Enter this heading.</h1>
<div></div>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
("p").mouseleave(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p>Move your mouse cursor over this statement.</p>
</body>
</html>