Categories
JavaScript Answers

How to Detect When the Mouse Leaves the Window with JavaScript?

Spread the love

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 0
  • event.clientX is less than or equal to 0
  • event.clientX is bigger than or equal to window.innerWidth
  • event.clientY is bigger than or equal to window.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 .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *