The jQuery hover() method executes two functions when you roam the mouse pointer over the selected element. The hover() method triggers both the mouseenter and mouseleave events.
Syntax:
$(selector).hover(inFunction,outFunction)
Parameter | Description |
---|---|
InFunction | It is a mandatory parameter. It is executed the function when mouseenter event occurs. |
OutFunction | It is an optional parameter. It is executed the function when mouseleave event occurs. |
Let's take an example to see the hover () effect. In this example, when you hover your mouse pointer over the selected element the the background color of that selected element will be changed.
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> $(document).ready(function(){ $("p").hover(function(){ $(this).css("background-color", "violet"); }, function(){ $(this).css("background-color", "green"); }); }); </script> </head> <body> <p>Hover your mouse pointer on me!</p> </body> </html>
Output:
Hover your mouse pointer on me!
Let's see another example of hover() event with the combination of fadeIn and fadeOut effects.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>hover demo</title> <style> ul { margin-left: 20px; color: black; } li { cursor: default; } span { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <ul> <li>Java</li> <li>SQL</li> <li class="fade">Android</li> <li class="fade">php</li> </ul> <script> $( "li" ).hover( function() { $( this ).append( $( "<span> ***</span>" ) ); }, function() { $( this ).find( "span:last" ).remove(); } ); $( "li.fade" ).hover(function() { $( this ).fadeOut( 100 ); $( this ).fadeIn( 500 ); }); </script> </body> </html>