Sometimes, we want to detect when the mouse leaves the window with JavaScript.
In this article, we’ll look at how to detect when the mouse leaves the window with JavaScript.
Detect When the Mouse Leaves the Window with JavaScript
To detect when the mouse leaves the window with JavaScript, we can add the mouseleave
event to document
.
For instance, we can write:
document.addEventListener("mouseleave", (event) => {
if (event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight)) {
console.log("I'm out");
}
});
We add a mouseleave
event listener with the addEventListener
method.
Then in the event listener, we check if one of the following conditions are met:
event.clientY
is less than or equal to 0event.clientX
is less than or equal to 0event.clientX
is bigger than or equal towindow.innerWidth
event.clientY
is bigger than or equal towindow.innerHeight
If any of the conditions are true
, then we know the mouse is out of the browser tab.
And therefore, “I'm out"
is logged.
Conclusion
To detect when the mouse leaves the window with JavaScript, we can add the mouseleave
event to document
.