How to check if mouse button exited 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 (or mousemove) event does not fire when the RAPIDLY mouse moves outside the browser window (my element is close to the edge). I decided that the best way to solve my problem is to check the timer if the mouse is inside the window or not, but I did not find a way to do this, since I need an event to shoot to get the mouse coordinates.

I'm new to javascript / jquery, but it seems like there should be a way to do this, but I definitely couldn't find it. Maybe I can make a mouse event fire and see if there is any xy value? Any idea how I can do this?

Thanks in advance!

+6
source share
6 answers

It looks like @Joshua Mills solved this problem here:

Although he was never officially chosen as an answer.

+6
source

You need to check the purpose of the event to make sure the mouse leaves the entire 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 nesting of elements to make sure that it really works.

+3
source

I think it will look

  <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> 
+1
source

It should be pretty 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 fires every time for me, at least.

0
source

Try:

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

I tried one by one and it actually works!

fooobar.com/questions/33625 / ...

I skip older browsers, so I cut the code to work in modern IE9 + browsers:

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

Here you see browser support

0
source

Source: https://habr.com/ru/post/906053/


All Articles