jQuery hover()

The jQuery hover() method is used to trigger both the mouseenter and mouseleave events, to execute two functions, i.e., when the mouse pointer roams over the selected element.

Syntax:

$(selector).hover(inFunction,outFunction)

In Function:

  • It is a mandatory parameter.
  • This parameter specifies the function to run when the mouseenter event occurs.

Out Function:

  • It is a mandatory parameter.
  • This parameter specifies the function to run when the mouseleave event occurs.

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").hover(function(){
$(this).css("background-color", "red");
}, function(){
$(this).css("background-color", "orange");
});
});
</script>
</head>
<body>
<p>Hover the mouse pointer on me and I will change my color!</p>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<head>
<style>
ul {
margin-left: 20px;
color: black;
}
li {
cursor: default;
}
span {
color: red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li>Burger</li>
<li>Pizza</li>
<li>Cold Drink</li>
<li>French Fries</li>
</ul>
<script>
$( "li" ).hover(
function() {
$( this ).append( $( "<span>My choice</span>" ) );
}, function() {
$( this ).find( "span:last" ).remove();
}
);
$( "li.fade" ).hover(function() {
$( this ).fadeOut( 100 );
$( this ).fadeIn( 500 );
});
</script>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com