jQuery mouseleave() method attaches mouse leave event handler function to html elements. This mouse leave event is triggered when mouse pointer leaves the html element. When mouse leave event is triggered, the associated event handler function executes. The event handler function is where we write our custom code to perform various actions.
jQuery mouseleave() Method Syntax
$(selector).mouseleave(function(){ //event handler function //This code executes when mouseleave event is triggered });
Here $(selector) is a jQuery selector to select html elements, which are attached to the event handler function using mouseleave() method. The event handler function executes when the mouse pointer leaves these selected html elements.
jQuery mouseleave() Example
In the following example we have two paragraphs but we want the mouseleave event to trigger only when the mouse pointer leaves the second paragraph, to achieve this, we have assigned an id to the second paragraph and attached the mouseleave event handler function to this paragraph using jQuery id selector and mouseleave() method.
When the mouse pointer leaves the paragraph with id “para”, an alert message “Mouse pointer leaves the paragraph” will be displayed.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#para").mouseleave(function(){ alert("Mouse pointer leaves the paragraph"); }); }); </script> </head> <body> <h2>jQuery mouseleave event example</h2> <p>This example is published on beginnersbook.com.</p> <p id="para">When mouse pointer leaves this paragraph, an alert message will be displayed.</p> </body> </html>
Output:
Before the mouse pointer leaves the paragraph with id “para”:
After the mouse pointer leaves the paragraph with id “para”:
Leave a Reply