5

QUESTION DOES NOT ALREADY HAVE AN ANSWER (if you can provide code that works instead of googling my question and linking to whatever answer comes up for the sweet sweet internet points then I will accept it as an answer. But since I have already been to all of those questions don't pretend like they work unless you can provide actual code that you have tested)

If you just do

$(window).on("mouseout", function() { alert("OUT"); });

you can mouseout on the left or right side of the window and it doesn't fire the event. I made a jsfiddle here but it actually works fine because there is a border around the iframe.

So what is the best way to know if a mouse has left the window? I can put a 1px border around the page (composed of 4 divs). I can monitor x/y and tell if the mouse is on an edge. But ideally $(window).on("mouseout", foo) would tell me when the mouse has left the window.

  • You can use a transparent border with `box-sizing:border-box;` – www139 Oct 07 '15 at 13:58
  • JQuery mouseleave also works, but I can't remember too much; I'll look into jquery mouseleave. – www139 Oct 07 '15 at 13:59
  • Take a look at this; http://stackoverflow.com/a/8873586/3011082 – www139 Oct 07 '15 at 14:01
  • 1
    Possible duplicate of [How can I check if the mouse exited the browser window using javascript/jquery?](http://stackoverflow.com/questions/8873508/how-can-i-check-if-the-mouse-exited-the-browser-window-using-javascript-jquery) – www139 Oct 07 '15 at 14:02
  • I copied and pasted your code here and it worked. I am using Firefox 41, jquery.min.js 2.1.4. – Rodrigo5244 Oct 10 '15 at 15:05

1 Answers1

0

This answer is working: https://stackoverflow.com/a/3187524/2831645

Using jQuery you can rewrite the code like this:

$(window).on("mouseout", function(e) {
    if(!e.relatedTarget || e.relatedTarget.nodeName == 'HTML') {
        alert('left window');
    }
});

The code has been tested on latests Firefox & Chrome.

Community
  • 1
  • 1
thibpat
  • 714
  • 5
  • 17
  • you da man! That works for me on both vertical and horizontal mouse outs. –  Oct 21 '15 at 14:29