7

I have a CSS3 animation at the top of my homepage that will start as soon as the page loads. The problem is if the user opens that page in a new tab but doesn't view it right away the animation will play even though they're not viewing that page.

Is there a way to only get the animation to start only after the user has that views that page?

Kind of like how if you open a youtube video in another hidden tab it won't automatically play until you open that tab. And also CodePen does the same if you open a pen in a new tab it wont start until you view that tab

nicael
  • 18,550
  • 13
  • 57
  • 90

2 Answers2

3

You'll want to use the visibility api: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API?redirectlocale=en-US&redirectslug=DOM%2FUsing_the_Page_Visibility_API

In particular, you'll want the document.hidden property and the visibilitychange event. You can use these to dynamically change your classes when the document.hidden property is false.

taylorc93
  • 3,676
  • 2
  • 20
  • 34
1

As mentioned there, you can check when the window is focused, i.e. user clicked (but not viewed though) it. How would you implement it?

You pick an id / class / tag, whatever. Style it, with animations also. Once that window is focused, you apply id/class to an element or create a new element with the tag / id / class. After the class is added, you either nullify the onfocus function, or check via a variable created for this purpose.

Example:

window.onfocus=function(){
   window.onfocus=null;
   document.getElementById("toBeAnimated").className="animatable";
}
#toBeAnimated{
  font-size:25px;
}
.animatable{
  transition: background-color 250ms linear;
  background-color:black;
  transition: color 250ms linear;
  color:white;
}
<div id="toBeAnimated">Focus on the snippet to animate me!</div>

Another option: you can apply the function to the onscroll event also, i.e. when the user starts to scroll your page.

Community
  • 1
  • 1
nicael
  • 18,550
  • 13
  • 57
  • 90