jQuery mouseenter() function example

jQuery mouseenter() function is used to bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

Syntax

$(selector).mouseenter( handler )
handler - A function to execute each time the event is triggered.
$(selector).mouseenter( [eventData ], handler )
  • eventData - An object containing data that will be passed to the event handler.
  • handler - A function to execute each time the event is triggered.

Examples

Example 1

Show texts when mouseenter and mouseout event triggering. mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>mouseenter demo</title>
    <style>
        div.out {
            width: 40%;
            height: 120px;
            margin: 0 15px;
            background-color: #d6edfc;
            float: left;
        }

        div.in {
            width: 60%;
            height: 60%;
            background-color: #fc0;
            margin: 10px auto;
        }

        p {
            line-height: 1em;
            margin: 0;
            padding: 0;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <div class="out overout">
        <p>move your mouse</p>
        <div class="in overout">
            <p>move your mouse</p>
            <p>0</p>
        </div>
        <p>0</p>
    </div>

    <div class="out enterleave">
        <p>move your mouse</p>
        <div class="in enterleave">
            <p>move your mouse</p>
            <p>0</p>
        </div>
        <p>0</p>
    </div>

    <script>
        var i = 0;
        $("div.overout")
            .mouseover(function() {
                $("p", this).first().text("mouse over");
                $("p", this).last().text(++i);
            })
            .mouseout(function() {
                $("p", this).first().text("mouse out");
            });

        var n = 0;
        $("div.enterleave")
            .mouseenter(function() {
                $("p", this).first().text("mouse enter");
                $("p", this).last().text(++n);
            })
            .mouseleave(function() {
                $("p", this).first().text("mouse leave");
            });
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

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").mouseenter(function() {
                alert("You entered p1!");
            });
        });
    </script>
</head>

<body>

    <p id="p1">Enter this paragraph.</p>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References


Comments