I'm running an animation on some elements that are set to opacity: 0;
in the CSS. The animation class is applied onClick, and, using keyframes, it changes the opacity from 0
to 1
(among other things).
Unfortunately, when the animation is over, the elements go back to opacity: 0
(in both Firefox and Chrome). My natural thinking would be that animated elements maintain the final state, overriding their original properties. Is this not true? And if not, how can I get the element to do so?
The code (prefixed versions not included):
@keyframes bubble { 0% { transform:scale(0.5); opacity:0.0; } 50% { transform:scale(1.2); opacity:0.5; } 100% { transform:scale(1.0); opacity:1.0; } }
CSS animations emit events, so you can use the animationend event to intervene when the animation ends. const element = document. getElementById("element-to-be-animated"); element. addEventListener("animationend", () => { // Set your final state here.
Alternatively, you can set the initial state of your class to how you want the animation to end, then * initialize * it at from / 0% .
To fade-in you want the last keyframe to be maintained and keep the opacity at 1. There is a CSS property called animation-fill-mode, this defines how elements are styled outside of the CSS animations. The values of the animation-fill-mode can be, none (default), forwards, backwards, or both.
The animation-fill-mode property specifies a style for the element when the animation is not playing (before it starts, after it ends, or both). CSS animations do not affect the element before the first keyframe is played or after the last keyframe is played.
Try adding animation-fill-mode: forwards;
. For example like this:
-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */ animation: bubble 1.0s forwards;
If you are using more animation attributes the shorthand is:
animation: bubble 2s linear 0.5s 1 normal forwards;
This gives:
bubble
animation name2s
durationlinear
timing-function0.5s
delay1
iteration-count (can be 'infinite
')normal
directionforwards
fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})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