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)
Note: If you specify only one function then it will be run for both the mouseenter and mouseleave event.
Parameters of jQuery hover() event
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. |
jQuery hover example
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!
Note: In the above example, the background color of the selected element is violet for mouseenter event and green for mouseleave event.
jQuery hover() example 2
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>
Leave a Reply