0

I'm using the following function (found in this really helpful post) to detect whether the mouse left the window :

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

addEvent(document, "mouseout", function (e)
{
  e = e ? e : window.event;
  var from = e.relatedTarget || e.toElement;
  if (!from || from.nodeName == "HTML")
  {
    console.log("left the window");
  }
});

However, this is not working when the mouse leaves the window really slowly or when the mouse is really close to the border of the window right before it leaves the window.

Is there a way around that, using either jQuery or pure Javascript?

Community
  • 1
  • 1
The Random Guy
  • 321
  • 2
  • 4
  • 10

2 Answers2

0

If you're using jquery, you can just bind the mouseout event:

$(document).on('mouseout', function () { console.log("left the window") });

You don't need to calculate any reference to the mouse. Since the event is bound directly to the document, that is effectually binding it to the confines of the page. Anywhere outside of the main content pane (e.g. tab bar, url bars, window borders, etc.) is outside of the document and would fire the mouseout. It won't fire under any other user circumstances.

Here is a working Fiddle Demo

Bic
  • 3,141
  • 18
  • 29
  • No this is not working. Due to event propagation I believe, it's detecting everything as a mouseout while you hover over the document. The jQuery people didn't get that one right unfortunately. – The Random Guy Jan 17 '14 at 21:43
  • Try it under real conditions. On the page we're on right now (it has jQuery). It's not working. – The Random Guy Jan 17 '14 at 21:47
  • hmm. What I did was use jQuery('body').on...etc.. and then in the callback check to see if the X or Y is a negative integer. As you are correct, it bubbles thru all the elements otherwise. If either of the axis are neg, then I know I left the viewable area. – james emanon Jan 17 '14 at 22:50
0

I have done this workaround detecting when they are near the edge of the page (15 pixels margin works well). I use this in conjunction with mouseout event)

var mouseNearWindowEdge = function(e) {
      var gap = 15;      
      var mp = { x: e.pageX-window.pageXOffset, y: e.pageY-window.pageYOffset };
      if (mp.x<gap || mp.y<gap || mp.x>window.innerWidth-gap || mp.y>window.innerHeight-gap) return true;
      return false;
    };

add event listener on mousemove and call the function.

Jay Byford-Rew
  • 5,736
  • 1
  • 35
  • 36