Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start CSS3 transition after user views page?

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

like image 391
Zainab Abounassif Avatar asked Dec 22 '15 16:12

Zainab Abounassif


2 Answers

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.

like image 168
taylorc93 Avatar answered Sep 28 '22 04:09

taylorc93


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.

like image 39
nicael Avatar answered Sep 28 '22 03:09

nicael