JavaScript mouseleave
The mouseleave
event is fired when the pointer leaves an element. This event is similar to the mouseout
event, but it has a few differences. The mouseleave
event is not fired when the pointer is moved from an element to its child elements, unlike the mouseout
event.
Syntax
element.addEventListener('mouseleave', function);
element
: The element on which the event is being listened for.function
: The function to be executed when the event is fired.
Example
<div id="box">Hover over me</div>
<script>
const box = document.getElementById('box');
box.addEventListener('mouseleave', () => {
console.log('Mouse left the box');
});
</script>
Output
When the user moves the mouse outside the box element, the console will log Mouse left the box
.
Explanation
In the above example, we first select the div
element with an id
of box
using the getElementById()
method. We then add an event listener to the box
element that listens for the mouseleave
event. When the event is fired (i.e., the user moves their pointer outside of the box
element), the function passed to addEventListener()
is executed, which logs a message to the console.
Use
The mouseleave
event can be used to do certain actions when the user moves their mouse outside of an element. For example, you can use this event to hide certain elements or display a message to the user.
Important Points
- The
mouseleave
event is similar to themouseout
event, but it doesn't fire when the pointer moves to its child elements. - The
mouseleave
event is not supported in older versions of Internet Explorer (IE 8 and earlier).
Summary
- The
mouseleave
event is fired when the user moves their pointer outside of an element. - The syntax for adding a
mouseleave
event listener to an element involves calling theaddEventListener()
method with themouseleave
event type and a function to be executed when the event is fired. - The
mouseleave
event can be useful for hiding or changing the display of certain elements when the user moves their mouse off of them.