How can I detect when the mouse leaves the window?

Viewed 134962

I want to be able to detect when the mouse leaves the window so I can stop events from firing while the user's mouse is elsewhere.

Any ideas of how to do this?

18 Answers

In order to detect mouseleave without taking in account the scroll bar and the autcomplete field or inspect :

document.addEventListener("mouseleave", function(event){

  if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
  {

     console.log("I'm out");

  }
});

Conditions explanations:

event.clientY <= 0  is when the mouse leave from the top
event.clientX <= 0  is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom

======================== EDIT ===============================

document.addEventListener("mouseleave") seems to be not fired on new firefox version, mouseleave need to be attached to an element like body, or a child element.

I suggest to use instead

document.body.addEventListener("mouseleave")

Or

window.addEventListener("mouseout")

Here is a 2021 answer:

You can use mouseleave (and mouseenter to detect when entering) in the html tag (tested in Chrome 91 and Firefox 90)

Try in Snippet below, by hovering in and out of it.

document.documentElement.addEventListener('mouseleave', () => console.log('out'))
document.documentElement.addEventListener('mouseenter', () => console.log('in'))

I tried one after other and found a best answer at the time:

https://stackoverflow.com/a/3187524/985399

I skip old browsers so I made the code shorter to work on modern browsers (IE9+)

    document.addEventListener("mouseout", function(e) {
        let t = e.relatedTarget || e.toElement;
        if (!t || t.nodeName == "HTML") {
          console.log("left window");
        }
    });

document.write("<br><br>PROBLEM<br><br><div>Mouseout trigg on HTML elements</div>")

Here you see the browser support

That was pretty short I thought

But a problem still remained because "mouseout" trigg on all elements in the document.

To prevent it from happen, use mouseleave (IE5.5+). See the good explanation in the link.

The following code works without triggering on elements inside the element to be inside or outside of. Try also drag-release outside the document.

var x = 0

document.addEventListener("mouseleave", function(e) { console.log(x++) 
})

document.write("<br><br>SOLUTION<br><br><div>Mouseleave do not trigg on HTML elements</div>")

You can set the event on any HTML element. Do not have the event on document.body though, because the windows scrollbar may shrink the body and fire when mouse pointer is abowe the scroll bar when you want to scroll but not want to trigg a mouseLeave event over it. Set it on document instead, as in the example.

I take back what i said. It is possible. I wrote this code, works perfectly.

window.onload = function() {

    $span = document.getElementById('text');

    window.onmouseout = function() {
        $span.innerHTML = "mouse out";  
    }

    window.onmousemove = function() {
        $span.innerHTML = "mouse in";   
    }

}

works in chrome, firefox, opera. Aint tested in IE but assume it works.

edit. IE as always causes trouble. To make it work in IE, replace the events from window to document:

window.onload = function() {

    $span = document.getElementById('text');

    document.onmousemove = function() {
        $span.innerHTML = "mouse move";
    }

    document.onmouseout = function() {
        $span.innerHTML = "mouse out";
    }

}

combine them for crossbrowser kick ass cursor detection o0 :P

See mouseover and mouseout.

var demo = document.getElementById('demo');
document.addEventListener("mouseout", function(e){demo.innerHTML="";});
document.addEventListener("mouseover", function(e){demo.innerHTML="";});
div { font-size:80vmin; position:absolute;
      left:50%; top:50%; transform:translate(-50%,-50%); }
<div id='demo'></div>

A combination of some of the answers here. And I included the code showing a model only once. And the model goes away when clicked anywhere else.

<script>
    var leave = 0
    //show modal when mouse off of page
    $("html").mouseleave(function() {
       //check for first time
       if (leave < 1) {
          modal.style.display = "block";
          leave = leave + 1;
       }
    });

    // Get the modal with id="id01"
       var modal = document.getElementById('id01');
            
    // When the user clicks anywhere outside of the modal, close it
       window.onclick = function(event) {
          if (event.target == modal) {
             modal.style.display = "none";
          }
       }
</script>

You could do an OnMouseOut function call on the body tag.

Related