Ask any question about CSS here... and get an instant response.
How can I make an animation restart when the user clicks on an element?
Asked on Nov 09, 2025
Answer
To restart an animation when a user clicks on an element, you can use JavaScript to remove and re-add the class that triggers the animation. This effectively resets the animation.
<!-- BEGIN COPY / PASTE -->
<style>
.animate {
animation: bounce 2s infinite;
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-30px); }
60% { transform: translateY(-15px); }
}
</style>
<div id="animatedElement" class="animate">Click me!</div>
<script>
const element = document.getElementById('animatedElement');
element.addEventListener('click', () => {
element.classList.remove('animate');
void element.offsetWidth; // Trigger reflow
element.classList.add('animate');
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The JavaScript snippet removes the "animate" class and immediately re-adds it to restart the animation.
- The line "void element.offsetWidth;" is a trick to force a reflow, ensuring the class removal is processed before re-adding it.
- This method works for CSS animations triggered by classes and is a common technique for restarting animations.
Recommended Links:
