jQuery Hover() event method; In this tutorial, you will learn what is jQuery hover event and how to use hover event with html elements.
jQuery Hover() Event Method with Example
The hover()
method in jQuery is used to attach event handlers to an element for both the “mouseenter” and “mouseleave” events. These events are triggered when the mouse pointer enters and leaves the selected HTML element’s boundaries. By using, you can conveniently set up actions to be performed when the mouse enters and exits the element.
Syntax of jQuery Hover() Event Method
$(selector).hover(inFunction,outFunction)
Parameters of jQuery Hover() Event Method
- InFunction :- It is a mandatory parameter. This is executed the function when mouseenter event occurs.
- OutFunction :- It is an optional parameter. This is executed the function when mouseleave event occurs.
Examples of jQuery Hover() Event Method
Let’s see example 1 of hover event
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $("#first").hover(function(){ $(this).css("background-color", "red"); }, function(){ $(this).css("background-color", "green"); }); }); </script> </head> <body> <h4 id="first">Hover your mouse pointer on here!</h4> </body> </html>
Result :-
Hover your mouse pointer on here!
In this above example 1, When we will cursor pointer on html elements, the jQuery hover method trigger.
Let’s see example 2 of hover event
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $("#second").hover(function(){ $( this ).append( $( "<b> Thank for reading </b>" ) ); }, function(){ $( this ).find( "b:last" ).remove(); }); }); </script> </head> <body> <h4 id="second">Hover your mouse pointer on here!</h4> </body> </html>
Result :-
Hover your mouse pointer on here!
In this above example 2, When we will cursor pointer on html elements, the jQuery hover method trigger and show text “thanks for reading”.