jQuery mouseleave()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery mouseleave()

The mouseleave() method adds an event handler function to an HTML element. This function is executed, when the mouse pointer leaves the HTML element.

When your mouse cursor leaves the selected element, it triggers the mouseleave event and once the mouseleave event is occurred, it executes the mouseleave() method attached with the event handler function to run.

This event is generally used together with mouseenter() event.

Syntax:

  1. $(selector).mouseleave()  

It triggers the mouseleave event for selected elements.

  1. $(selector).mouseleave(function)

It adds a function to the mouseleave event.

Parameters of jQuery mouseleave() event

Parameter Description
Function It is an optional parameter. It executes itself when the mouseleave event is triggered.

Example of jQuery mouseleave() event

Let's take an example to demonstrate jQuery mouseleave() event.

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>    
  5. <script>    
  6. $(document).ready(function(){    
  7.     $("#h1").mouseleave(function(){    
  8.        $( "div" ).text( "Bye Bye... leaving heading" ).show().fadeOut( 2000 );   
  9.     });    
  10. });    
  11. </script>    
  12. </head>    
  13. <body>    
  14. <h1 id="h1">Enter this heading.</h1>   
  15. <div></div>   
  16. </body>    
  17. </html>    

Test it Now

Output:

Enter this heading.

jQuery mouseleave() event example 2

Let's see another example of jQuery mouseleave() event.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("p").mouseenter(function(){  
  8.         $("p").css("background-color", "red");  
  9.     });  
  10.     $("p").mouseleave(function(){  
  11.         $("p").css("background-color", "blue");  
  12.     });  
  13. });  
  14. </script>  
  15. </head>  
  16. <body>  
  17. <p>Move your mouse cursor over this statement.</p>  
  18. </body>  
  19. </html>  
  20.     

Test it Now

Output:

Move your mouse cursor over this statement.