Skip to content Skip to sidebar Skip to footer

How Can I Check If The Mouse Exited The Browser Window Using Javascript/jquery?

I need a way to check and see if the mouse is outside the browser window. The problem is that the mouseout event (or mousemove) isn't triggered when the mouse RAPIDLY moves outside

Solution 1:

Seems like @Joshua Mills solved this problem here:

Although it was never officially selected as an answer.

Solution 2:

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><divclass="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.

Solution 3:

I think, this will look like

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

Solution 4:

Try with:

document.addEventListener("mouseleave", function(e){
    if( e.clientY < 0 )
    {
         alert("I'm out!");
    }
}, false);

Solution 5:

It should be fairly simple:

document.onmouseout = function() {
  alert('out');
};

Or jQuery style:

$(document).mouseout(function() {
  alert('out');
});

Fiddle: http://jsfiddle.net/xjJAB/

Tested in IE8, chrome, FF. The event triggers every time for me at least.

Post a Comment for "How Can I Check If The Mouse Exited The Browser Window Using Javascript/jquery?"