How can I check if the mouse exited the browser window using javascript/jquery?

Seems like @Joshua Mills solved this problem here:

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

Although it was never officially selected as an answer.


You need to check the target of the event to make sure the mouse left the whole page.

Live Demo

JS

$(function() {
    var $window = $(window),
        $html = $('html');
    $window.on('mouseleave', function(event) {
        if (!$html.is(event.target))
            return;
        $('.comeback').removeClass('hidden');
    });
    $window.on('mouseenter', function(event) {
        $('.comeback').addClass('hidden');
    });
});

HTML

<div>
    <div>
        Test
    </div>
    <div class="comeback">
        Come back!
    </div>
    <div>
        Test
    </div>
</div>

CSS

.hidden { display: none; }

The test case includes some element nesting to verify that it really works.


I think, this will look like

 <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>