What is onmouseleave event in JavaScript?

The onmouseleave event triggers when the mouse pointer moves out of an element. It fires only when the mouse completely leaves the element boundary.

Syntax

element.onmouseleave = function() {
    // Code to execute when mouse leaves
};

// Or using addEventListener
element.addEventListener('mouseleave', function() {
    // Code to execute
});

Example: Basic Mouse Leave Event

Here's how to implement the onmouseleave event:

<html>
<head>
    <script>
        function sayHello() {
            alert("Mouse Leave");
        }
    </script>
</head>
<body>
    <p onmouseleave="sayHello()" style="padding: 20px; background-color: lightblue;">
        Hover over this text, then move your mouse away to trigger the event.
    </p>
</body>
</html>

Example: Using addEventListener

A more modern approach using addEventListener:

<html>
<head>
    <style>
        .hover-box {
            width: 200px;
            height: 100px;
            background-color: lightgreen;
            padding: 20px;
            margin: 20px;
            border: 2px solid green;
        }
    </style>
</head>
<body>
    <div id="myBox" class="hover-box">
        Move mouse over and then leave this box
    </div>
    <p id="status">Status: Waiting for mouse action</p>

    <script>
        const box = document.getElementById('myBox');
        const status = document.getElementById('status');

        box.addEventListener('mouseenter', function() {
            status.textContent = "Status: Mouse entered the box";
            box.style.backgroundColor = 'lightcoral';
        });

        box.addEventListener('mouseleave', function() {
            status.textContent = "Status: Mouse left the box";
            box.style.backgroundColor = 'lightgreen';
        });
    </script>
</body>
</html>

Key Points

  • onmouseleave fires when the mouse pointer exits an element
  • It does not bubble up to parent elements
  • Often paired with onmouseenter for interactive effects
  • Different from onmouseout which can trigger on child elements

Comparison: mouseleave vs mouseout

Event Bubbling Triggers on Child Elements
mouseleave No No
mouseout Yes Yes

Conclusion

The onmouseleave event is perfect for creating hover effects and interactive UI elements. Use it with onmouseenter for smooth user interactions without unwanted triggering on child elements.

Updated on: 2026-03-15T23:18:59+05:30

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements