How can I detect when the mouse leaves the window? How can I detect when the mouse leaves the window? javascript javascript

How can I detect when the mouse leaves the window?


Please keep in mind that my answer has aged a lot.

This type of behavior is usually desired while implementing drag-drop behavior on an html page. The solution below was tested on IE 8.0.6, FireFox 3.6.6, Opera 10.53, and Safari 4 on an MS Windows XP machine.
First a little function from Peter-Paul Koch; cross browser event handler:

function addEvent(obj, evt, fn) {    if (obj.addEventListener) {        obj.addEventListener(evt, fn, false);    }    else if (obj.attachEvent) {        obj.attachEvent("on" + evt, fn);    }}

And then use this method to attach an event handler to the document objects mouseout event:

addEvent(document, "mouseout", function(e) {    e = e ? e : window.event;    var from = e.relatedTarget || e.toElement;    if (!from || from.nodeName == "HTML") {        // stop your drag event here        // for now we can just use an alert        alert("left window");    }});

Finally, here is an html page with the script embedded for debugging:

<html><head><script type="text/javascript">function addEvent(obj, evt, fn) {    if (obj.addEventListener) {        obj.addEventListener(evt, fn, false);    }    else if (obj.attachEvent) {        obj.attachEvent("on" + evt, fn);    }}addEvent(window,"load",function(e) {    addEvent(document, "mouseout", function(e) {        e = e ? e : window.event;        var from = e.relatedTarget || e.toElement;        if (!from || from.nodeName == "HTML") {            // stop your drag event here            // for now we can just use an alert            alert("left window");        }    });});</script></head><body></body></html>


If you are using jQuery then how about this short and sweet code -

$(document).mouseleave(function () {    console.log('out');});

This event will trigger whenever the mouse is not in your page as you want. Just change the function to do whatever you want.

And you could also use:

$(document).mouseenter(function () {    console.log('in');});

To trigger when the mouse enters back to the page again.

Source: https://stackoverflow.com/a/16029966/895724


This works for me:

addEvent(document, 'mouseout', function(evt) {  if (evt.toElement == null && evt.relatedTarget == null) {    alert("left window");  }});