window.focus listener EXAMPLE

Looking for a way to prevent animations from firing when multiple tabs are open. Quick & Dirty solution...

by bcmoney

HTML

<a id="start" href="#start">Start</a> | <a id="stop" href="#stop">Stop</a>
<div id="container">
    <div id="animated">Animated content</div>
</div>

CSS

body {
    overflow:hidden;
}
#container {    
    width:100%;
    height:100%;
}
#animated { 
    width: 120px;
    position: absolute;
    left: 2px;
    top: 20px;
    padding: 50px;
    background: skyblue;
    color: white
}

JavaScript

// configurations - yes Global = bad, only for testing purposes
var animation = 1;
var startTime = undefined;
var FPS = 60; //frames per second
var AVAILABLE_WIDTH = $("#container").width() || "800px";
var animation = null;
var FOCUSED = false;
var timestamp = new Date().getTime();
var PAGE_ID = $("body").attr("id") + "-animated-"+timestamp;


/* 
 * continueScrolling
 *   keeps the animation going if we're still in focus
 * @param p String  unique pageID passthrough parameter
 */
function continueScrolling(p) {
    //DEBUG:  console.log('FUNCTION p: '+p);
    if (FOCUSED === true && p === PAGE_ID) {
        animation = setTimeout(function(){scrollRight(p)}, FPS);
    } else {
        clearTimeout(animation);
        $('#animated').stop(true, true);
    }
}

/*
 * scrollRight
 *   calling point for a linear left-to-right animation, increments the left positioning every n seconds, where n is the number of Frames Per Second to run the animation at.
 * activated manually or on page focus
 * @param p String  initially the global PAGE_ID, later could be fired from any number of open tabs, so it is supposed to check against the currently focused page's tab and decide whether to animate or not based on timestamp value passed in
 */
var scrollRight = function(p) {
    time =  +new Date;
    startTime = (startTime !== undefined) ? startTime : time-FPS;
  move = ((time - startTime)/10 % AVAILABLE_WIDTH)+"px";
    //DEBUG:  console.log('P:'+p+' | T:'+time+' | ST:'+startTime+' | W:'+AVAILABLE_WIDTH+'\n'+move);
  $('#animated').animate({
       "left":move
    }, 
    1000/FPS, 
    "linear",
     function() {
    //DEBUG:  console.log('CALLBACK p: '+p);         
       continueScrolling(p);
     }
  );
}  


/* catch page focus, pause animations when not in focus */
$(window).blur(function(){
   FOCUSED = false;
  $('#stop').click();
});

$(window).focus(function(){
   FOCUSED = true;
  $('#start').click();   
});


/* manual override controls */   ...