Javascript detect active window and mouse moving stop

Facebook wont update the new post on wall if you didnt move your mouse on the screen. It is because Facebook want to save bandwidth when you are not viewing facebook website. For example, if you open facebook website, but you away from keyboard/computer for 3 hours, maybe u go toilet or go out to work, facebook will not waste bandwidth to update new posts on wall. Facebook know you are afk by detecting your mouse movement. The same as Gmail switches your chat status from away to online / busy when you werent having your gmail tab active for a while.

For my case, my website keep auto reload a javascript function for every 10 seconds by setInterval( "checklatestmsgidLive();", 10000 ); The function will still keep reloading the function even when the user is viewing other website on other tab. How to stop reloading it when the user is on other tab? How to make it reload the function only when the user is viewing my website? To do that, I just need to use window.onfocus and window.onblur function, but too bad IE cannot support it, so need modify the codes, adding if (/*@cc_on!@*/false) to detect whether or not the browser is IE. So now I can detect the user is on other tab or is active on my website. I also added mouse movement detection to determine the user is viewing my website by document.onmousemove. Too bad there is no document.onmousestop function, so need to do some trick on document.onmousemove function. Below is the codes :

<div id="test" style="color: black;">
mouse is stop</div">

<div id="test2" style="color: black;">
pause</div">


<script type="text/javascript">
document.onmousemove = (function() {                   
  var onmousestop = function() {
   document.getElementById(test).innerHTML="mouse is stop!!!";
  }, thread;

  return function() {
      document.getElementById(test).innerHTML="mouse is moving!!!";
    clearTimeout(thread);
    thread = setTimeout(onmousestop, 200);
  };
})();

function onBlur() {
    document.getElementById(test2).innerHTML="window is inactive, pause everything!";
};
function onFocus(){
     document.getElementById(test2).innerHTML="window is active";
};

if (/*@cc_on!@*/false) { // check if it is Internet Explorer the double c on is jsript that only ie has
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onload=window.onfocus = onFocus;
    window.onblur = onBlur;
}
</script>

You can view the Demo here.

Related Posts by Categories

0 komentar:

Posting Komentar