jQuery hover()

Filed Under: jQuery

jQuery hover() function fires when the mouse pointer enters and leaves the selected HTML element. jQuery hover function will attach two event handlers to execute when the mouse enters and leaves the element.

jQuery hover

The hover() method attaches handlers for mouse enter and mouse leave events.

The syntax for using hover():

  • hover(handlerIn, handlerOut)

handlerIn is a function to execute when the mouse enters the html element and handlerOut function executes when the mouse leaves the element.

  • hover (handlerInOut)

Using this you can attach a single handler – handlerInOut that will execute with the mouse enter and mouse leave events. This function is shorthand for $( selector ).on( "mouseenter mouseleave", handlerInOut );.

jQuery hover example

Following example demonstrates jQuery hover() function usage.


<!DOCTYPE html>
<html>
<head>
<title>jQuery hover</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script> 
$(document).ready(function(){
  $("div").hover(
     function() {
        $( this ).append( $( "<span> : Now You are a Super *****</span>" ) );
  }, function() {
        $( this ).find( "span:last" ).remove();
     }
);
});
</script>
 
<style> 
.divClass1
{
    padding:5px;
    text-align:center;
    background-color:yellow;
    border:solid 1px;
}

span {
    color: red;
}
</style>
</head>
<body>

<div class="divClass1">Enter JournalDev</div>

</body>
</html>

In this example, you can see the hover() function is attached with two handlers – append() method is the function executed when you enter the element and it will append a <span> element. When you leave the element find() method finds the <span> element and it’s removed from the parent element, which is the <div> element in this example.

Below is the output of above HTML page, just hover over it and notice the jQuery hover function in action.

That’s all for a simple jQuery hover() function example, it’s a very useful method for creating great animation and effects.

Comments

  1. Matheux says:

    Thanks Pankaj,

    I didn’t have the exact problem, but through your syntax I was able to resolve my issue.

    I used your outline to apply a class change on buttons based upon the hover attribute.

    basically:
    $(document).ready(function(){
    $(“button”).hover(function(){
    $( this ).removeClass( “class” );
    $( this ).addClass( “other class” );
    },function() {
    $( this ).removeClass( “other class” );
    $( this ).addClass( “class” );
    });
    });

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages