With css @keyframes
I'm trying to attach some animation to an element when it is clicked.
.animate {
animation-name: action;
animation-duration: 2s;
animation-timing-function: linear;
background-color: green;
}
@keyframes action {
0% {
background-color: gray;
}
50% {
background-color: red;
}
100% {
background-color: green;
}
}
DEMO
The .animate
class is added on click, and the box animates from gray to green. But now I would like to animate back to gray when I click it again (toggle functionality). I tried using the same animation using animation-direction: reverse
but no animation was played. The animation should not play initially (I encountered that a couple of times). Any suggestion how I can achieve that?
The key to restarting a CSS animation is to set the animation-name of an animation to 'none' and then setting it back to the original animation. As you can see this requires two steps. One to switch it to a different animation and one to set it back.
The animation-play-state CSS property sets whether an animation is running or paused.
Go to Animations > Advanced Animation > Add Animation and select the animation you want to add. Next, go to Animations > Advanced Animation > Animation Pane. In the Animation Pane, select the animated shape or other object that you want to trigger to play when you click it.
I would consider using the animation-play-state
property and also use infinite
and alternate
. The idea is to run the animation and stop it when it ends, then run it again and so on:
const div = document.querySelector('.target')
div.addEventListener('click', (e) => {
div.classList.add('play');
setTimeout(function() {
div.classList.remove('play');
},2000)
})
.target {
width: 100px;
height: 100px;
background-color: gray;
cursor: pointer;
animation: action 2s linear alternate infinite;
animation-play-state:paused;
}
.play {
animation-play-state:running;
}
@keyframes action {
0% {
background-color: gray;
}
50% {
background-color: red;
}
100% {
background-color: green;
}
}
<div class="target">
</div>
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