Bubble Foundry


(Non)Persistence of CSS Animated Properties

by Peter.

For Fronting Motion I am exploring the use of CSS3 animations with keyframes. However, there are some gotchas associated with the persistence of the transformed properties that I only realized.

To explain, consider the following keyframes:

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes moveRight {
  from {
    left: 0px;
  }
  to {
    left: 100px;
  }
}

If we apply the fadein animation to a DOMElement called box, we might do so like so:

  box.style.animation = "fadein 5s";

box will now fade in over 5 seconds. But once the animation is done, it will return to its original opacity!

The reason is because of the animation-fill-mode property. The default is none, which means that none of its styles will be applied to box before or after the animation is executed.

So, we can quickly fix it by saying that the animation should be filled forwards:

  box.style.animation = "fadein 5s forwards";

This means that the final opacity value will persist after the animation ends.

Great, but what happens if we apply our second animation after the first?

  box.style.animation = "fadein 5s forwards";
 
  setTimeout(function() {
    box.style.animation = "moveRight 5s forwards";
  }, 6000);

First the fadein animation will be applied and then, 6 seconds after the first one started and so (approximately) 1 second after it ended, the moveRight animation will be applied.

And this is what will happen, but you’ll notice that box‘s opacity will jump back to its original value before fadein as soon as moveRight is applied.

Why is this?

It’s pretty simple: the first animation assignment completely overwrote the first, and so all the changes it made, even though they were kept forwards by animation-fill-mode are removed.

Unfortunately, for this reason it is difficult, if not impossible, to apply multiple animations on an object at separate times. You can list multiple keyframes in a single animation assignment, though.