5

I would like to play an animation and make sure that the visitor will see that. My problem is that, when somebody opens a new browser tab in the background (for example by clicking a link with target="_blank") then the document's ready event is not enough, because there is a chance that the visitor will watch that site only after a few minutes, so he won't see the animation from the beginning or anything at all.

Is there a way to start my animation (by running the proper JavaScript function) only when the user clicks to that browser tab? Is there an event or any other workaround that would mimic this behavior? It doesn't matter if the code will be executed only on the first time or every time the user clicks to the browser tab.

totymedli
  • 29,531
  • 22
  • 131
  • 165

2 Answers2

7

Try requestAnimationFrame. If the tab is not active, then the animation frame will not occur until it is.

I use this to defer "auto-update" on some of my pages, and it certainly works - I've even gotten positive feedback on it :)

brasofilo
  • 25,496
  • 15
  • 91
  • 179
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

According to this answer:How to tell if browser/tab is active

You can see if a tab is active using window.onfocus and window.onblur events.

var isActive;

window.onfocus = function () { 
  isActive = true; 
}; 

window.onblur = function () { 
  isActive = false; 
}; 
Community
  • 1
  • 1
Delayer
  • 409
  • 1
  • 5
  • 17