jQuery hover()

jQuery hover() method attaches mouse hover event listener to the HTML Element.

jQuery hover is a compound event. In includes mouse-enter and mouse-leave event. jQuery hover() method accepts two functions as arguments. First function is executed when mouse enter event is occured and the second function is executed when the mouse leave event is triggered.

Syntax - jQuery hover()

Following is the syntax to use jQuery hover() method :

To attach a mouse hover event listener to HTML Element(s)
$("selector").hover(function(){ // for mouse enter event
  // your javascript/jquery statements here
}, function(){ // for mouse leave event
  // your javascript/jquery statements here
});

Examples - jQuery hover()

Following examples help you understand the usage of jQuery hover() method :

Example - Change text of paragraphs when mouse hovers them

In the following example, when mouse hover occurs, mouse enter and mouse leave events trigger respective functions provided as arguments to hover() function.

<!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 ).text("You entered my area !");
  },
  function(){
    $( this ).text("You left me!");
  }); 
});
</script>
</head>
<body>

<p>Hover on me with mouse.</p>
<p>Hover on me too.</p>

</body>
</html>
Try Online

Example - Change DIV's background color when mouse hovers it

Following example has a div on which mouse hover event is attached. When mouse hovers on the div, background color of it is changed.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $( "div" ).hover(function(){
    $( this ).css("background","#FA0");
  },
  function(){
    $( this ).css("background","#CCC");
  }); 
});
</script>
</head>
<body>

<div style="width:200px;height:200px;background:#CCC;"></div>

</body>
</html>
Try Online

Conclusion

In this jQuery Tutorial, we have learnt jQuery hover() method : Syntax and Usage with examples.