Sub topic 15
Going further with the Web Animations API
The Web Animations API (WAAPI) is the JavaScript interface to the same animation engine that runs CSS transitions and keyframe animations. This chapter assumes you can write @keyframes rules, know the animation and transition longhands, and can use addEventListener, promises and async/await. It covers the working model, playback control, the gotchas that differ from CSS, and when to choose WAAPI over a stylesheet.
The working model
A WAAPI animation is an Animation object built from two parts:
- An effect (a
KeyframeEffect) holds the target element, the keyframes and the timing. It plays the role of@keyframesplus theanimation-*properties. - A timeline supplies the clock. By default this is
document.timeline, which advances with the page.
element.animate(keyframes, options) creates both and starts playing immediately. It returns the Animation object, which you use to control playback.
const card = document.querySelector('.card');
const fade = card.animate(
[
{ opacity: 0, transform: 'translateY(8px)' },
{ opacity: 1, transform: 'none' }
],
{ duration: 400, easing: 'ease-out', fill: 'both' }
);The effect is the same as the CSS fade-in example from earlier chapters, but you now hold a handle on it.
Keyframe formats
Keyframes can be an array of objects, as above, or an object of arrays:
card.animate(
{ opacity: [0, 1], transform: ['scale(0.95)', 'scale(1)'] },
{ duration: 300, fill: 'both' }
);Property names are camelCase (backgroundColor, not background-color). The CSS float property is written cssFloat. A keyframe can also carry:
offset, a number from 0 to 1 that works like the percentage in@keyframes.easing, which applies between that keyframe and the next, asanimation-timing-functiondoes inside a CSS keyframe.
card.animate(
[
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)', offset: 0.7, easing: 'ease-out' },
{ transform: 'translateX(240px)' }
],
{ duration: 800, fill: 'both' }
);If you leave out the first or last keyframe's value, the browser fills it in from the element's current computed style. This is called an implicit keyframe. It is useful for animating from wherever the element currently is.
Timing options
The options map directly onto the CSS longhands, with different names and units:
| CSS | WAAPI option | Notes |
|---|---|---|
| `animation-duration: 400ms` | `duration: 400` | Plain number of milliseconds |
| `animation-delay` | `delay` | Milliseconds |
| `animation-iteration-count: infinite` | `iterations: Infinity` | The JavaScript value `Infinity` |
| `animation-direction` | `direction` | Same keywords |
| `animation-fill-mode` | `fill` | Same keywords |
| `animation-timing-function` | `easing` | Same values, but the default differs |
Gotchas that differ from CSS
The default easing is linear
CSS animations default to ease. WAAPI defaults to linear. An animation ported without an explicit easing will feel mechanical. Always set easing yourself.
Fill mode defaults to none
Like CSS, WAAPI snaps back to the element's normal style when the animation ends unless you set fill. Many people add fill: 'forwards' to make the end state stick. That creates a new problem, covered next.
Filling forwards keeps the animation alive
An animation with fill: 'forwards' finishes but stays attached to the element. It continues to override the element's styles, and it takes priority over normal CSS changes you make later. A later el.style.opacity = '1' can appear to do nothing. Browsers may also keep these animations in memory.
The fix is commitStyles(). It writes the animation's current computed values into the element's inline style, so you can cancel the animation without losing the result.
async function slideRight(el) {
const animation = el.animate(
[{ transform: 'translateX(0)' }, { transform: 'translateX(120px)' }],
{ duration: 300, easing: 'ease-out', fill: 'forwards' }
);
await animation.finished;
animation.commitStyles();
animation.cancel();
}Call commitStyles() before cancel(). After a cancel, the effect no longer produces values to commit.
Controlling playback
CSS gives you animation-play-state and little else. An Animation object gives you methods, properties and a promise.
| Member | What it does |
|---|---|
| `play()`, `pause()` | Start or freeze playback |
| `reverse()` | Play backwards from the current position |
| `finish()` | Jump to the end state |
| `cancel()` | Stop and remove all effects, returning to idle |
| `playbackRate` | Speed multiplier. `2` is double speed and `-1` is reverse |
| `currentTime` | Position in milliseconds. You can read it and set it |
| `playState` | `idle`, `running`, `paused` or `finished` |
| `finished` | A promise that resolves when playback ends |
Setting currentTime is how you build scrubbing, such as a slider that drives an animation:
const slide = card.animate(
[{ transform: 'translateX(0)' }, { transform: 'translateX(300px)' }],
{ duration: 1000, easing: 'linear', fill: 'both' }
);
slide.pause();
const slider = document.querySelector('#scrub');
slider.addEventListener('input', () => {
slide.currentTime = Number(slider.value) * 1000;
});Here #scrub is an <input type="range" min="0" max="1" step="0.01">. The animation is paused, so only the slider moves it. The linear easing makes position proportional to time.
Waiting for completion
The finished promise replaces the animationend listener for most code. It reads in order:
async function fadeOutAndRemove(el) {
const animation = el.animate(
[{ opacity: 1 }, { opacity: 0 }],
{ duration: 250, easing: 'ease-in', fill: 'forwards' }
);
try {
await animation.finished;
el.remove();
} catch (error) {
if (error.name !== 'AbortError') throw error;
}
}If anything calls cancel(), the promise rejects with an AbortError. Without the try/catch, a cancelled animation produces an unhandled rejection. Handle the cancel path deliberately. In the code above, a cancelled fade leaves the element in the DOM.
If you prefer events, animation.onfinish and animation.oncancel exist. They fire for a single Animation, so you don't need to filter by animationName the way you filter propertyName on transitionend.
Inspecting existing animations
CSS transitions and CSS animations are also Animation objects. getAnimations() returns them, as CSSTransition and CSSAnimation instances, alongside any created with animate().
for (const animation of document.getAnimations()) {
console.log(animation.constructor.name, animation.playState);
}
document.querySelector('.button').getAnimations().forEach((a) => a.pause());You can pause, reverse or scrub an animation that you wrote in CSS. This is useful for debugging and for tests that need to put motion in a known state. It also lets you build a "pause all motion" control with document.getAnimations().forEach((a) => a.pause()).
Respecting reduced motion in JavaScript
The prefers-reduced-motion media query in CSS does not affect animations you start from JavaScript. You must check it yourself with matchMedia:
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
function animateIn(el) {
return el.animate(
[{ opacity: 0, transform: 'translateY(8px)' }, { opacity: 1, transform: 'none' }],
{
duration: reduceMotion.matches ? 0 : 300,
easing: 'ease-out',
fill: 'both'
}
);
}A duration of 0 still ends in the correct final state and still resolves finished. Your code that waits on the promise keeps working, which is better than skipping the call.
Choosing between CSS and WAAPI
Use CSS when the motion is a fixed state change that a designer could describe in a stylesheet. Use WAAPI when JavaScript has to decide something at runtime.
| Need | Better choice |
|---|---|
| Hover and focus feedback | CSS transition |
| Fixed looping effect such as a pulse | CSS `@keyframes` |
| Start position computed from layout or user input | WAAPI |
| Pause, reverse or scrub from code | WAAPI |
| Run code after the animation, in sequence | WAAPI with `await` |
| Remove an element after it fades out | WAAPI |
Both approaches run on the same engine. Animating transform and opacity from WAAPI is as compositor-friendly as it is from CSS, and the same performance rules apply.
Common errors
- Using hyphenated property names such as
'background-color'in a keyframe. UsebackgroundColor. - Forgetting that the default easing is
linear. - Setting
fill: 'forwards'and never committing or cancelling, so later style changes are ignored. - Not catching the
AbortErrorfromfinished. - Passing durations as strings such as
'300ms'. Use the number300. - Ignoring
prefers-reduced-motionbecause the CSS media query is in place. It does not coveranimate().
Exercise
You write el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, fill: 'forwards' }). The fade works, but a few seconds later your code sets el.style.opacity = '0.5' and nothing changes. What causes this, and how do you fix it?
Show answer
The animation finished but, because of fill: 'forwards', it stays attached and keeps overriding the element's opacity, and animation values take priority over inline styles. To fix it, wait for animation.finished, call animation.commitStyles() to write the final values into the inline style, then call animation.cancel(). After that, normal style changes apply. Also set an explicit easing, since the default is linear.
Exercise
A user clicks "Dismiss" on a banner. You run await banner.animate(..., { duration: 200 }).finished and then remove the banner. A second script cancels the animation when the user clicks "Undo". What happens to your await, and how should you handle it?
Show answer
The finished promise rejects with an AbortError when the animation is cancelled, so the await throws and the removal line is skipped. Wrap the await in try/catch, ignore errors whose name is AbortError, and rethrow anything else. The banner then stays in the DOM, which is the right result for "Undo".