The jQuery hover()
function can be used to perform both mouseenter and mouseleave events. The method can execute two different functions together when you take your mouse to the element or mouseout from the element.
hover()
, it will execute on both mouseenter and mouseout events.Syntax
The syntax of jQuery hover() Function is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
inFunction | Specify the function to execute at the time when the mouseenter event occurs. Mandatory |
outFunction | Specify the function to execute at the time when the mouseout events occur. Optional |
jQuery hover() Function Examples
Let’s see some useful examples of jQuery hover()
function method.
Example 1: Change the Background on mouseenter and mouseout events
You can create a hover effect to change the background on mouse enter and mouse out. It requires to use the hover()
within which you have to use the css()
function of jQuery.
1 2 3 4 5 6 7 8 9 10 11 12 |
<script> $(document).ready(function(){ $('p').hover(function(){ $(this).css("background", "blue"); $(this).css("padding", "15px"); }, function(){ $(this).css("background", "yellow"); $(this).css("padding", "15px"); }); }); </script> <p>Hover me to see mouseenter and mouseout effects</p> |
Output
Hover me to see mouseenter and mouseout effects
The above example contains the text content. When you hover over the above text content, it will add a blue background with some padding to the text content. On mouseout, it changes the background color to yellow.
Example 2: Fade In and Fade Out on jQuery hover() Effect
If you want to fade in and fade out the <div>
element on mouseenter and mouseout. It uses the fadeIn()
and fadeIn()
function of jQuery for the effect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('button').hover(function(){ $('div').fadeIn(1000); },function(){ $('div').fadeOut(1000); }); }); </script> <button type="button">Hover me to see Effects</button> <div> <p><strong>Name</strong>: Nick Wilson</p> <p><strong>Mobile</strong>: 0123456789</p> </div> |
Output
The above example contains the button element and the div content. You have to hover over the above button to fade in and fade out the div element using jQuery.
You may also like to read