Detecting if the browser window is moved with JavaScript? Detecting if the browser window is moved with JavaScript? windows windows

Detecting if the browser window is moved with JavaScript?


I can only think of this (heavy) work-around, where you check if window.screenX and window.screenY have changed every x milliseconds

var oldX = window.screenX,    oldY = window.screenY;var interval = setInterval(function(){  if(oldX != window.screenX || oldY != window.screenY){    console.log('moved!');  } else {    console.log('not moved!');  }  oldX = window.screenX;  oldY = window.screenY;}, 500);

Though I would not recommend this -- it might be slow and I'm not sure if screenX and screenY are supported by all browsers


A potentially more optimised version of this is to only check for window movement when outside of the window combined with Harmen's answer:

var interval;window.addEventListener("mouseout", function(evt){   if (evt.toElement === null && evt.relatedTarget === null) {    //if outside the window...    if (console) console.log("out");    interval = setInterval(function () {      //do something with evt.screenX/evt.screenY    }, 250);  } else {    //if inside the window...    if (console) console.log("in");    clearInterval(interval);  }});

If using jQuery, it may normalise screenX/Y in this case so it's worth running a few tests on that. Jquery would use this format instead of addEventListener:

$(window).on('mouseout', function () {});

If you are moving the window in Windows OS via alt + Space, and find that windows resizes are ignored, I would recommend adding an extra level of detection via keypress events.


Re the first answer: I use the 'poll window position' in production code. It's a very lightweight thing to do. Asking for a couple of object properties twice a second is not going to slow anything down. Cross-browser window position is given by:

function get_window_x_pos(){   var winx;   if(window.screenX)      winx=window.screenX;   else if(window.screenLeft)      winx=window.screenLeft;   return winx;}

and similarly for vertical position. In my code I use this to fire an AJAX event off to the server to store position and size of the window so next time it will open where it was the last time (I'm probably moving to HTML5 local storage soon.) One little wrinkle you might want to cover is not generating spurious updates while the window is being dragged. The way to handle this is to register when the window has been moved for the first time and only trigger an update when two subsequent polls of window position return the same value. A further complication is for windows which allow resizing from all sides. If the left or top side are dragged, the DOM will give you a resize event, but the nominal window position will have altered as well.