jQuery hover
The hover()
method attaches handlers for mouse enter and mouse leave events.
The syntax for using hover():
- hover(handlerIn, handlerOut)
handlerIn
is a function to execute when the mouse enters the html element and handlerOut
function executes when the mouse leaves the element.
Using this you can attach a single handler – handlerInOut
that will execute with the mouse enter and mouse leave events. This function is shorthand for $( selector ).on( "mouseenter mouseleave", handlerInOut );
.
jQuery hover example
Following example demonstrates jQuery hover() function usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE html> <html> <head> <title>jQuery hover</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(document).ready(function(){ $("div").hover( function() { $( this ).append( $( "<span> : Now You are a Super *****</span>" ) ); }, function() { $( this ).find( "span:last" ).remove(); } ); }); </script> <style> .divClass1 { padding:5px; text-align:center; background-color:yellow; border:solid 1px; } span { color: red; } </style> </head> <body> <div class="divClass1">Enter JournalDev</div> </body> </html> |
In this example, you can see the hover() function is attached with two handlers – append() method is the function executed when you enter the element and it will append a <span> element. When you leave the element find() method finds the <span> element and it’s removed from the parent element, which is the <div> element in this example.
Below is the output of above HTML page, just hover over it and notice the jQuery hover function in action.
That’s all for a simple jQuery hover() function example, it’s a very useful method for creating great animation and effects.