Sub topic 15
Going further with the Web Animations API
This chapter assumes you can write @keyframes rules and the animation shorthand, and that you can select elements and add event listeners in JavaScript. The Web Animations API (WAAPI) runs the same kind of animation from JavaScript and gives you an object to control it.
From CSS to `Element.animate()`
element.animate(keyframes, options) starts an animation immediately and returns an Animation object. The keyframes are an array of objects, and the options hold the timing.
const card = document.querySelector('.card');
card.animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 300, easing: 'ease-out', fill: 'both' }
);The browser runs this on the same animation engine as CSS. It can use the compositor (the browser stage that moves layers on the GPU) for transform and opacity, so it is just as cheap.
The options map directly to the CSS properties you already know:
| CSS property | WAAPI option |
|---|---|
| `animation-duration` | `duration` (milliseconds, as a number) |
| `animation-timing-function` | `easing` |
| `animation-delay` | `delay` |
| `animation-iteration-count` | `iterations` (`Infinity` for endless) |
| `animation-direction` | `direction` |
| `animation-fill-mode` | `fill` |
Two details differ from CSS. Keyframe property names are camelCase, so you write backgroundColor, not background-color. Iterations use the number Infinity, not the keyword infinite.
Controlling a running animation
The returned Animation object is the main reason to use WAAPI. It has methods such as play(), pause(), reverse(), finish() and cancel(). It also has properties such as playbackRate and currentTime.
const badge = document.querySelector('.badge');
const pulse = badge.animate(
[
{ transform: 'scale(1)' },
{ transform: 'scale(1.1)' },
{ transform: 'scale(1)' }
],
{ duration: 1500, easing: 'ease-in-out', iterations: Infinity }
);
badge.addEventListener('click', () => {
if (pulse.playState === 'running') {
pulse.pause();
} else {
pulse.play();
}
});Knowing when it ends
In place of animationend, the Animation object has a finished promise. It resolves once, when the animation completes, so you can use then or await.
const fade = document.querySelector('.card').animate(
[{ opacity: 1 }, { opacity: 0 }],
{ duration: 300, fill: 'forwards' }
);
fade.finished.then(() => {
document.querySelector('.card').remove();
});The promise rejects if you call cancel(). Add a catch if your code might cancel.
Respecting reduced motion
CSS media queries do not apply to animations you start in JavaScript, so check the preference yourself.
const prefersReducedMotion = window
.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!prefersReducedMotion) {
document.querySelector('.badge').animate(
[{ transform: 'scale(1)' }, { transform: 'scale(1.1)' }],
{ duration: 750, direction: 'alternate', iterations: Infinity }
);
}Common errors
- Nothing moves.
durationdefaults to 0, so the animation finishes at once. Always set it. - The element snaps back. Without
fill: 'forwards'or'both', the element returns to its CSS value when the animation ends. - Forgetting that WAAPI styles are temporary. The end values are not written to the element. Call
animation.commitStyles()beforecancel()if you want to keep them.
Choosing between CSS and WAAPI
Use CSS when the motion is fixed and tied to a state such as :hover or a class. Use WAAPI when values are computed at runtime, when you need to pause, reverse or scrub the animation, or when you need to wait for it to finish before your code continues.
Exercise
A fade-out animation started with element.animate() runs for 300 ms, and the element jumps back to full opacity as soon as it ends. Which option fixes this, and what must you do if you want to keep the final style after calling cancel()?
Show answer
Set fill: 'forwards' (or 'both') in the options so the end keyframe stays applied. To keep the final style after cancel(), call animation.commitStyles() first, because WAAPI end values are not written to the element on their own.