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.
How to detect when the mouse leaves the window with JavaScript?
To detect when the mouse leaves the window with JavaScript, we listen for the documentElement
‘s mouseenter and mouseleave events.
For instance, we write
document.documentElement.addEventListener("mouseleave", () =>
console.log("out")
);
document.documentElement.addEventListener("mouseenter", () =>
console.log("in")
);
to call document.documentElement.addEventListener
to listen for the mouseleave and mouseenter events.
If mouseleave event is triggered on documentElement
then the mouse left the window.
If mouseenterevent is triggered on documentElement
then the mouse comes into the window.
Conclusion
To detect when the mouse leaves the window with JavaScript, we listen for the documentElement
‘s mouseenter and mouseleave events.