Be aware of css animation

January 22, 2022

Photo by atiabii from Pexels

Be aware of the "dark side" of css animations fill-mode. We usually use "fill-mode" when we want the element the browser just animated to keep the last frame's style. For example when we animate an element from left to right, we want it to stay at the right side.

How we set fill-mode?

CSS

1.animated {
2 animation: example-animation 500ms linear forwards /* <-- fill-mode */;
3}
4
5@keyframes example-animation {
6 from {
7 width: 50px;
8 }
9 to {
10 width: 200px;
11 }
12}

Javascript

1element.animate([
2 {width: '50px'},
3 {width: '200px'},
4], {
5 duration: 500,
6 fill: 'forwards'
7})

What's the catch?

Once the animation is done, the style can't be overridden.

What if we do want to change the style afterwards?

It depends on how the animation initiated.

CSS animation

Split the animation property to another class and remove the class when you want to change the style

Javascript animate

animate method returns an Animation object. To reset the style, call Animation.cancel()

https://stackoverflow.com/a/70732331/863110
© 2022 - Moshe Feuchtwander