1

Folks,

Someone refreshes all their tabs. My tab is in a non-active non-foreground tab.

This runs: jQuery(document).ready().

So:

  • How do I get my animation to run only when the tab becomes active?

AND

  • How do I get it to run if the tab is foreground and active anyway?

I have tried:

<script>jQuery( document ).ready(function() { jQuery(window).focus(function () { setTimeout(function(){ jQuery('.juiz-outdated-message').addClass('active'); }, 500); }); });</script>

This happens on so many sites I can't find any resources on how to do it, though?!

Harry
  • 11
  • 1
  • @gurvinder372, thanks for your comment but as you can see from the code fragment in my question I've already tried that and it doesn't work. – Harry Oct 19 '17 at 09:53

2 Answers2

0

How do I get it to run if the tab is foreground and active anyway?

Using the page visibility api, you need to handle the visibilitychange event.

How do I get my animation to run only when the tab becomes active?

Here is an example code from the documentation link shared.

function handleVisibilityChange() {
  if (document.hidden) {
    pauseSimulation();
  } else  {
    startSimulation();
  }
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);

Shared documentation link has other fallback given as well for different browsers, and the same has been discussed here in detail.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I see, thank you. So there's no 'firstfocus' or similar event. I just have to check if it's got focus in the first instance. Thank you! – Harry Oct 19 '17 at 10:04
0

Answering my own question using the logic of what @gurvinder372 kindly provided:

function animateeeee() { //the magic function
 setTimeout(function(){ jQuery('.juiz-outdated-message').addClass('active'); }, 500);
}; 
jQuery( document ).ready(function() { //runs on DOM ready
    if (document.hasFocus()) { //if we already have focus...
     animateeeee(); //do it now
     } else { //otherwise
  jQuery(window).focus(function() { //bind to focus
   animateeeee();// then run
  });       
     }; 
 });
Harry
  • 11
  • 1