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.clientYis less than or equal to 0
- event.clientXis less than or equal to 0
- event.clientXis bigger than or equal to- window.innerWidth
- event.clientYis 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.
