Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
onmouseleavefires when the mouse pointer exits an element - It does not bubble up to parent elements
- Often paired with
onmouseenterfor interactive effects - Different from
onmouseoutwhich 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.
Advertisements
