jQuery mouseleave()

mouseleave() handles one of the Mouse Events, mouse leaving the area spanned by HTML element.

jquery mouseleave() method could be called on HTML Element(s) filtered via jQuery Selector.

Syntax - jQuery mouseleave()

Following is the syntax to use jQuery mouseleave() method :

To attach a mouse leave listener to HTML Element(s)
 $("selector").mouseleave(function(){
  // your javascript/jquery statements here
});

Examples - jQuery mouseleave()

Following examples help you understand the usage of jQuery mouseleave() method :

Example - Change text of Paragraph when mouse leaves

In the following example, we have attached mouse leave event listener to paragraph elements. Whenever the mouse leaves the area spanned by a paragraph, the mouse leave event is triggered and runs the code in the function, which here is changing the text of paragraph.

<!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(){
    $( this ).text("You left !");
  });
});
</script>
</head>
<body>

<p>A paragraph</p>
<p>Another paragraph</p>

</body>
</html>
Try Online

Example - Mouse enter and Mouse leave events attached to a div

Following example, contains a div that is a colored rectangle box. We have attached event listeners for mouse-enter and mouse-leave events. When the mouse enters the div, mouseenter event is triggered and when the mouse leaves the div, mouseleave event is triggered.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#colorBox").mouseenter(function(){
    $( this ).css("background-color","#484");
    $( this ).text("You entered mouse into the area that I span.").css("color","white");
  });
  $("#colorBox").mouseleave(function(){
    $( this ).css("background-color","#448");
    $( this ).text("You left.").css("color","white");
  });
});
</script>
</head>
<body>

<div id="colorBox" style="width:300px;height:200px;background-color:#CCC;padding:10px;"></div>

</body>
</html>
Try Online

Conclusion

In this jQuery Tutorial, we have learnt jQuery mouseleave() method : Syntax and Usage with examples.