jQuery hover() example

jQuery hover() function is used to bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

Syntax

$(selector).hover( handlerIn, handlerOut )
handlerIn - A function to execute when the mouse pointer enters the element. 
handlerOut - A function to execute when the mouse pointer leaves the element.

Examples

Example 1

To add a special style to list items that are being hovered over, try:
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>hover demo</title>
    <style>
        ul {
            margin-left: 20px;
            color: blue;
        }

        li {
            cursor: default;
        }

        span {
            color: red;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <ul>
        <li>Milk</li>
        <li>Bread</li>
        <li class="fade">Chips</li>
        <li class="fade">Socks</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>
Output:
Milk
Bread
Chips
Socks

Example 2

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#p1").hover(function() {
                    alert("You entered p1!");
                },
                function() {
                    alert("Bye! You now leave p1!");
                });
        });
    </script>
</head>

<body>

    <p id="p1">This is a paragraph.</p>

</body>

</html>
Output:
This is a paragraph.

References

Comments