jquery
  1. jquery-mouseleave

JQuery mouseleave()

JQuery mouseleave() is a method that allows you to execute a function when the mouse pointer leaves an HTML element.

Syntax

The basic syntax for mouseleave() method is as follows:

$(selector).mouseleave(function)

Use

mouseleave() method is useful when you want to trigger an event when the mouse pointer leaves an HTML element, such as hiding a dropdown menu or an overlay image.

Example

Here is an example of using mouseleave() method to hide an overlay image:

<!DOCTYPE html>
<html>
<head>
    <title>Using mouseleave() in jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #overlay {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
        }
        #overlay img {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            max-width: 80%;
            max-height: 80%;
        }


    </style>
</head>
<body>
    <h1>Mouseleave Example</h1>
    <p>Hover over the image to see the overlay</p>
    <img src="https://static.additionalsheet.com/images//others/josh.jpg" alt="example image" class="img">
    <div id="overlay">
        <img src="https://static.additionalsheet.com/images//others/josh.jpg" alt="overlay image">
    </div>
    <script>
        $(document).ready(function() {
            $("img").mouseenter(function() {
                $("#overlay").css("display", "block");
            });
            $("img").mouseleave(function() {
                $("#overlay").css("display", "none");
            });
        });
    </script>
</body>
</html>
Try Playground

In this example, when the user hovers over the image, the mouseenter() method is used to display the overlay by changing the display style property to block. When the user moves the mouse pointer away from the image, the mouseleave() method is used to hide the overlay by changing the display style property to none.

Summary

JQuery mouseleave() method is a simple yet powerful way to execute a function when the mouse pointer leaves an HTML element. It can be used for a variety of purposes, such as hiding dropdown menus or overlay images. By combining mouseleave() with mouseenter() method, you can create dynamic and interactive web pages with ease.

Published on: