In this lesson, you will learn about the jQuery hover event, which is similar to mouse enter and mouse leave events. The hover event is fired when the mouse pointer enters and leaves the elements.

Introduction to Hover event in jQuery

The syntax of the hover event is:

.hover(function_for_mouseIn(){}, function_for_mouseOut(){});

This is a short form of:

$("element").mouseenter( function_for_mouseIn(){}).mouseleave(function_for_mouseOut(){});

If you specify only one function in the argument list, it will be executed for both the mouse enter and mouse leave events.

The first argument is mandatory, whereas the second argument is optional and can be skipped.

Example of Hover event in jQuery

Hover event example

In this example, we have created a list of four fruits as list items. When a user hovers the mouse over a name of the fruit, a red checkbox appears before the name of the list item. As soon as the user takes the mouse away from the list item, the checkmark disappears.

The HTML

<div id="container">
   <ul>
      <li>Strawbery</li>
      <li>Banana</li>
      <li class="fade">Apple</li>
      <li class="fade">Oranges</li>
   </ul>
</div>

The CSS

#container{margin:20px; padding:10px; border:1px solid #ccc; width:400px;}
ul{ list-style:none;margin-left: 20px;}
li { cursor: default;}
span { color: red;}

The jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> 
<script>
    $(document).ready(function() {
        $("li").hover(
            function() {
                $(this).prepend($("<span>&#10004;</span>"));
            },
            function() {
                $(this).find("span:last").remove();
            }
        );
    }); 
</script>

If you like this article or have some questions, please leave it in the comments section below.

jQuery Keyboard Events Tutorial Home jQuery ‘on’ Function

 

Last modified: July 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.