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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With