shauneba
shauneba

Reputation: 2172

Do CSS animations still happen when invisible?

I have an element that functions as a loading indicator. It's always present on my page, and is shown/hidden by adding/removing a class that alters its opacity and z-index. The element contains an image that is animated using CSS.

I'm concerned that this will be inefficient for the page, as the animation may still be happening invisibly when the loader isn't on screen.

What I've Tried

I made it so that the animation only functions when the element has the visible class, but this causes a jarring effect as the animation stops as soon as the class is removed, before the loader has had a change to fade out. Adding a transition to the animation didn't seem to have any effect.

Upvotes: 3

Views: 386

Answers (2)

morgandigital
morgandigital

Reputation: 66

Yes they do. Please see the following fiddle ==> JS FIDDLE SHOWING CHANGE

css

@keyframes anim{
    0%{margin-left:0;}
    100%{margin-left:80%;}
}
@-webkit-keyframes anim{
    0%{margin-left:0;}
    100%{margin-left:80%;}
}
h3{
    float:left;
    position:absolute;
}
div{
    visibility:hidden;
    background:black;
    width:50px;
    height:50px;
    float:left;
    animation: anim 5s;
    -webkit-animation: anim 5s infinite; /* Safari and Chrome */
}

html

<div id="div">
   Div
</div>
<h3></h3>

js

setInterval(function() {
    jQuery('h3').text('Margin is:'+ jQuery('div').css('margin-left'))
},1000);

^ shows the result in the h3

Upvotes: 5

myajouri
myajouri

Reputation: 3114

While not sure if animations still take place on an element when it's hidden, you can use animation-iteration-count to end the animation after a certain number of iterations.

  • Use class="is-hidden" to hide the loader when not needed.
  • When .is-hidden is applied to the loader, change the animation-iteration-count of the spinner from infinity to, say, 5.

This will make the spinner do exactly 5 more spins and then end the animation. These 5 spins will take place while the loader is fading out. Obviously, you could increase the number of iterations/spins if 5 is not enough to cover the fade out duration.

LIVE DEMO (add and remove .is-hidden to .loader)

/* CSS */

@keyframes spin {
  to { transform: rotateZ(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to   { opacity: 1; }
}

@keyframes fadeOut {
  from { opacity: 1; }  
  to   { opacity: 0; }
}

.loader {
  /* loader styles... */

  animation: fadeIn 1s forwards;
}

.spinner {
  /* spinner styles... */

  animation: spin 0.5s linear infinite;
}

.loader.is-hidden {
  animation: fadeOut 1s forwards;
}

.loader.is-hidden .spinner {
  animation-iteration-count: 5;
}

Upvotes: 1

Related Questions