Adding a pause to an infinitely looping CSS3 animation

CSS Adding Pauses to Infinitely Looping CSS3 Animations

In this article, we’ll show you how to add a pause effect to an infinitely looping CSS3 animation using CSS code. CSS3 animations are a powerful tool for creating eye-catching web effects with a few simple lines of code. However, in some cases, you may want to add a pause function during an animation, giving the user control over how the animation plays and stops.

Read more: CSS Tutorial

Using the animation-play-state property in CSS

To add a pause effect to a CSS3 animation, we can use the CSS animation-play-state property. This property controls the animation’s play state and has two possible values: running for running the animation normally, and paused for pausing the animation.


Here is a simple example demonstrating how to use the animation-play-state property to achieve a paused animation effect:

@keyframes move { 
0% { 
transform: translateX(0); 
} 
100% { 
transform: translateX(200px); 
} 
} 

.moving-box { 
width: 100px; 
height: 100px; 
background-color: red; 
position: relative; 
animation: move 3s infinite; 
} 

.moving-box.paused { 
animation-play-state: paused; 
} 

In the code above, we create a keyframe animation called move to move a red box from the left to the right. In the .moving-box style, we set the animation to repeat indefinitely and set its initial state to running (the default) using the animation-play-state property. We also added an additional rule to the .moving-box.paused style to set the animation’s state to paused.

To allow the user to pause and play the animation, we can add an event handler via JavaScript:

const movingBox = document.querySelector('.moving-box');

movingBox.addEventListener('click', function() {
this.classList.toggle('paused');
});

In the JavaScript code above, we select the .moving-box element and add a click event handler to it. When the user clicks the element, the paused class is added or removed, toggling the animation’s play state.

Now, we can view this example in a browser and test it. When we click the animation element, it will immediately pause or resume, giving the user some flexibility.

Summary

By using the animation-play-state property, we can easily add pause functionality to infinitely looping CSS3 animations. By adding a click event handler to the animation element, we give the user control over the animation. This simple yet effective method improves user experience and interactivity. I hope this article helps you understand the pause effect in CSS3 animations!

Leave a Reply

Your email address will not be published. Required fields are marked *