CSS animations are a powerful way to add visual effects and transitions to your website. However, there may be times when you want to pause or stop an animation, whether it’s for user experience or performance reasons. In this blog post, we’ll explore different methods of stopping CSS animations using both CSS and JavaScript.
1. Using the ‘animation-play-state’ Property
The easiest way to pause an animation is by using the animation-play-state property. This property accepts two values: running and paused. By default, an animation is set to run. To pause an animation, simply set the property value to ‘paused’.
Here’s an example:
The CSS code:
.paused { animation-play-state: paused; }
The JavaScript code:
function toggleAnimation() { var element = document.querySelector('.example-animation'); element.classList.toggle('paused'); }
2. Removing the Animation Property
Another way to stop an animation is by removing the animation property from the element. This can be done by setting the property value to ‘none’ or by removing the class that holds the animation.
Here’s an example using inline styles:
The JavaScript code:
function stopAnimation() { var element = document.getElementById('example2'); element.style.animation = 'none'; }
3. Using ‘animationiteration’ Event Listener
If you want to stop an animation after it has completed a certain number of iterations, you can make use of the animationiteration event. This event fires each time an animation iteration completes. You can then use JavaScript to update the animation-play-state property or remove the animation property.
Here’s an example:
The JavaScript code:
var count = 0; var element = document.getElementById('example3'); element.addEventListener('animationiteration', function() { count++; if (count === 3) { // Stop animation after 3 iterations element.style.animationPlayState = 'paused'; } });
And there you have it. With these three methods, you can easily control and stop CSS animations on your website as needed. By combining CSS with JavaScript, you can create dynamic and interactive animations that greatly enhance user experience.