jQuery hover

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

ParameterDescription
InFunctionIt is a mandatory parameter. It is executed the function when mouseenter event occurs.
OutFunctionIt 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.


  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("p").hover(function(){  
  8.         $(this).css("background-color", "violet");  
  9.         }, function(){  
  10.         $(this).css("background-color", "green");  
  11.     });  
  12. });  
  13. </script>  
  14. </head>  
  15. <body>  
  16. <p>Hover your mouse pointer on me!</p>  
  17. </body>  
  18. </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>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *