When working with animations, it’s essential to ensure they are accessible to everyone. According to WCAG SC 2.2.2: Pause, Stop, Hide, users must be able to pause, stop, or hide animations that last more than 5 seconds. Let's break down how you can use CSS and JavaScript to create an animation that users can control.
A simple animation
We'll start by creating a simple animation using CSS keyframes. This animation moves a box horizontally across the screen.
<div class="animated-box"></div>
<style>
.animated-box {
width: 100px;
height: 100px;
background-color: #3498db;
animation: move 4s infinite;
}
@keyframes move {
0% { transform: translateX(0); }
50% { transform: translateX(200px); }
100% { transform: translateX(0); }
}
</style>
Adding play state
Next, we introduce the animation-play-state
property. This property allows us to control whether the animation is running or paused. We use a CSS variable, --play-state
, to set the default state of the animation.
:root {
--play-state: running;
}
.animated-box {
animation-play-state: var(--play-state);
}
Here, we define a --play-state
variable at the root level and set its initial value to running. The animation will run initially, but this variable gives us a way to control it later.
Adding control with javascript
We add a button that allows users to pause/play the animation by updating the --play-state
variable
<button id="toggle-btn">Pause Animation</button>
<script>
const toggleButton = document.getElementById('toggle-btn');
const root = document.documentElement;
toggleButton.addEventListener('click', () => {
const currentPlayState = getComputedStyle(root).getPropertyValue('--play-state').trim();
if (currentPlayState === 'running') {
root.style.setProperty('--play-state', 'paused');
toggleButton.textContent = 'Resume Animation';
} else {
root.style.setProperty('--play-state', 'running');
toggleButton.textContent = 'Pause Animation';
}
});
</script>
We use getComputedStyle
to get the current value of the --play-state
variable. Depending on whether the animation is running or paused, we toggle the value and also update the text of the button accordingly.
You can find the complete working example on codepen
By implementing simple solutions like animation-play-state
and providing controls for animations, you help create a more inclusive digital experience.
Top comments (3)
If there is more than one animation on a page is it possible to have a separate play/pause button for each one?
Yes, you can have separate control buttons for each of the animations, or a single button to control all the animations. You pretty much have flexibility to do what you want here
So how would you assign a button to a specific animation if there was multiple animations running on a page.