The toast in the @keyframes lesson can already enter, wait and leave by itself. But what if you want to pause it from JavaScript, play a dialog's animation backwards when it is cancelled halfway through, or wait for the animation to end before the next step? For that there is the Web Animations API (WAAPI): @keyframes written from JavaScript with element.animate().
The difference from CSS: animate() returns an Animation object. This object works like the remote of a video player, and the animation is the video. With that remote you can pause, continue, play backwards, jump to a given time, change the speed, and ask to be told when the video ends.
element.animate(keyframes, options)
This code makes the toast enter in 200 ms:
const toast = document.querySelector('.toast');
const entry = toast.animate(
[
{ opacity: 0, transform: 'translateY(16px)' }, // first keyframe (from)
{ opacity: 1, transform: 'none' }, // last keyframe (to)
],
{ duration: 200, easing: 'ease-out' } // options
);
- The first argument, the keyframes: an array with one object per keyframe. Property names are camelCase (
backgroundColor, notbackground-color), and values are strings as in CSS. The short form works too: one object with an array of values per property,{ opacity: [0, 1] }. - The second argument, the options:
durationin milliseconds (a number),easing(a CSS string), plusdelay,iterations(Infinityto repeat forever),directionandfill. - The animation starts right away, and
animate()returns anAnimationobject. Right after the call, itsplayState(its playing state) is'running', and itspending(still waiting to start) istrueuntil the first frame.
In the exercise, you put those two arguments together as one object { keyframes, options } and print them as JSON. A 500 ms fade-in prints like this:
const fade = {
keyframes: [{ opacity: 0 }, { opacity: 1 }],
options: { duration: 500, easing: 'ease-out', fill: 'forwards' },
};
console.log(JSON.stringify(fade.keyframes)); // [{"opacity":0},{"opacity":1}]
console.log(JSON.stringify(fade.options)); // {"duration":500,"easing":"ease-out","fill":"forwards"}
element.animate(fade.keyframes, fade.options);
fill: 'forwards' here holds opacity 1 after the fade ends. When that's right and when it becomes a problem is covered in the fill section below.
Animation: the remote
These are the buttons of that remote. anim is the Animation object that animate() returns:
| Call | What happens |
|---|---|
anim.pause() |
stops where it is; playState becomes 'paused' |
anim.play() |
continues from the last currentTime |
anim.reverse() |
turns around from where it is now |
anim.finish() |
jumps to the end; playState is 'finished' right away |
anim.cancel() |
removes its effect, the element goes back to its CSS; playState 'idle', currentTime null |
anim.currentTime = 2500 |
jumps to millisecond 2,500 |
anim.updatePlaybackRate(2) |
twice as fast (or set anim.playbackRate) |
We tried them on the 5 second bar of the toast (its code is in the section "The whole toast" below). Paused at 300 ms, its currentTime was still 300 after another 300 ms. Played again, 200 ms later its currentTime was 501. So the time really stops while it is paused.
Waiting for the end: finished
anim.finished is a Promise, an object that stands for a result that only exists later. This Promise settles when the animation ends, including through finish(). Use await inside an async function, so the next code waits for that Promise:
await entry.finished; // carry on only after its 200 ms entry has ended
This is more accurate than setTimeout(..., 200), because a timeout doesn't know when the animation is paused, sped up or reversed. Two things to know:
- After
finish(),playStateis'finished'right away, but the Promise settles a moment later (asynchronously: after the code that is running now ends). Then thefinishevent happens. This order is the same in all three browsers. cancel()makesfinishedreject with anAbortError. The message differs per browser: Chromium "The user aborted a request.", WebKit and Firefox "The operation was aborted.". If theawaitisn't wrapped intry/catch, that rejection becomes an unhandled error.
The whole toast, paused on hover
The toast "Booking sent. Mrs. Sri will confirm on WhatsApp." enters in 200 ms. Then it stays 5 seconds with a shrinking bar. The bar stops while the pointer is over the toast. After that, the toast leaves in 150 ms:
async function showToast() {
const toast = document.querySelector('.toast'); // <div class="toast" role="status">
const bar = toast.querySelector('.bar');
toast.hidden = false;
toast.animate(
[{ opacity: 0, transform: 'translateY(16px)' }, { opacity: 1, transform: 'none' }],
{ duration: 200, easing: 'ease-out' }
);
const timer = bar.animate(
[{ transform: 'scaleX(1)' }, { transform: 'scaleX(0)' }],
{ duration: 5000, easing: 'linear' }
);
toast.onpointerenter = () => timer.pause(); // pointed at: its time stops
toast.onpointerleave = () => timer.play(); // carries on with the time left
try {
await timer.finished; // 5 seconds shown, not counting pauses
} catch {
toast.hidden = true; // cancelled with cancel(): hide it at once
return;
}
const exit = toast.animate(
[{ opacity: 1, transform: 'none' }, { opacity: 0, transform: 'translateY(16px)' }],
{ duration: 150, easing: 'ease-in', fill: 'forwards' }
);
await exit.finished;
toast.hidden = true;
exit.cancel(); // drop its forwards effect
}
- The entry has no
fill, because its end style (opacity: 1) is already in the toast's CSS. So there's nothing to hold. - The 5 second bar,
timer, is a WAAPI animation too. The toast stays on screen while the code waits fortimer.finished. So when the bar pauses on hover, the toast's time on screen grows by itself. If the toast has a button, pause it also when keyboard focus moves into the toast (focusin), and continue when the focus leaves (focusout). - The exit uses
fill: 'forwards'so the toast doesn't flash (appear again for a moment) beforehiddenis set. After that,cancel()removes its effect.
fill, commitStyles and persist
Without fill, an animation's effect is gone as soon as the animation ends, and the element goes back to its CSS. If the toast's CSS writes opacity: 0 as the starting state, the toast vanishes again right after entering (we measured: opacity back to 0).
Before reading on, take a guess: the "Booking sent" toast enters with fill: 'forwards'. Then some other code writes toast.style.opacity = '0' to hide it. Does the toast disappear?
The answer: the toast doesn't disappear. fill: 'forwards' holds the last keyframe, but the animation stays attached to the element and beats inline styles (styles written through toast.style). We wrote toast.style.opacity = '0' after a forwards animation had ended. The opacity the browser computed was still 1 in Chromium 147, WebKit 26.4 and Firefox 146. toast.getAnimations().length, the number of animations attached to the toast, is still 1.
The fix: write the end result into the inline style, then release the animation:
entry.commitStyles(); // style="opacity: 1; transform: translateY(0px);"
entry.cancel(); // the animation is let go, getAnimations().length becomes 0
toast.style.opacity = '0'; // now it works
The browser also removes replaced animations by itself. We animated translateX three times in a row with fill: 'forwards'. The two older animations were removed automatically (their replaceState is 'removed'), and only the last one remained. If you really need them all to stay, call anim.persist() (replaceState becomes 'persisted').
A practical rule: put the end state in CSS and animate without fill, or use commitStyles() then cancel(). Since Chrome 144, Firefox 142 and Safari 26.2, commitStyles() also writes the end state of a finished animation that has no fill (in Chromium 156: opacity: 1). Older browsers need fill for that.
🤔 getAnimations() and composite
element.getAnimations() returns every animation active on that element, including CSS transitions (a CSSTransition object) and CSS animations (CSSAnimation). So you can wait for a CSS transition from JavaScript. Promise.all below waits until the finished Promises of all the animations on card have settled:
await Promise.all(card.getAnimations().map((a) => a.finished));
The composite option sets how the keyframes combine with the value already there. The default is 'replace': the keyframes overwrite that value. Say a card with transform: translateX(10px) is animated with scale(0.96) when pressed. The card loses its 10 px shift (we measured: matrix(0.96, 0, 0, 0.96, 0, 0); the last two numbers are the x and y shift). With composite: 'add', the scale is added to that shift: matrix(0.96, 0, 0, 0.96, 10, 0). Supported in Chrome 84, Firefox 80, Safari 16.
WAAPI, CSS, or requestAnimationFrame?
- CSS (transitions,
@keyframes) for changes CSS triggers: hover, classes, attributes. - WAAPI when you need control from JavaScript: pause, reverse, jumping in time, waiting for
finished, or keyframe values from data. Fortransformandopacity, WAAPI still runs on the compositor thread like CSS. With the main thread busy for 500 ms, WAAPI and a CSS transition both drew 60 frames, rAF only 1. - requestAnimationFrame when you compute every frame yourself: physics, canvas.
element.animate() has been available since Chrome 36, Firefox 48, Safari 13.1. finished, commitStyles() and persist() have been available since Chrome 84, Firefox 75 (finished Firefox 63), Safari 13.1. Safe to use in every modern browser.
⚠️ Why does it stay still, stay attached, or throw an error?
- Duration written in seconds.
animate(kf, 0.3)means a duration of 0.3 milliseconds. We checked:getTiming().durationis0.3. Write300. fill: 'forwards'everywhere. The animation stays attached and overrides inline styles. Use CSS as the end state, orcommitStyles()+cancel().- Property names with hyphens.
{ 'background-color': ... }is silently ignored in all three browsers. WritebackgroundColor. await anim.finishedwithouttry/catch.cancel()rejects it with anAbortError.setTimeoutto wait for an animation.setTimeoutdoesn't stop when the animation is paused.
TL;DR: The Web Animations API (WAAPI) is @keyframes written from JavaScript. element.animate(keyframes, options) takes the keyframes as an array of objects with camelCase property names (backgroundColor), and options { duration: ms, easing, fill, ... }. The result is an Animation object that starts right away. This object is like a video player remote: pause(), play(), reverse(), finish(), cancel(), currentTime, playbackRate. await anim.finished waits until the animation ends, and rejects with AbortError on cancel(). Mrs. Sri's toast waits for its 5 second bar, which pauses on hover. fill: 'forwards' holds the last keyframe, but overrides inline styles (style.opacity = '0' has no effect). commitStyles() + cancel() move the end result into the inline style. The browser removes forwards animations that are replaced, and persist() prevents that. getAnimations() also finds CSS transitions, and composite: 'add' adds onto the existing transform. Use WAAPI for UI animation that needs control, rAF for physics and canvas.
⚡ @keyframes from JavaScript
Write:
const entry = toast.animate(
[
{ opacity: 0, transform: 'translateY(16px)' }, // first keyframe (from)
{ opacity: 1, transform: 'none' }, // last keyframe (to)
],
{ duration: 200, easing: 'ease-out' } // options
);
Meaning: This code makes the element toast enter in 200 ms, with @keyframes written from JavaScript (the Web Animations API). The first argument is the keyframes: an array of objects with camelCase property names (backgroundColor, not background-color). The second argument is the options, and duration is written in milliseconds. animate() starts the animation right away and returns an Animation object, kept here in entry.
⚡ A video player remote
Meaning: The Animation object from animate() works like a video player remote for its animation: pause() stops where it is, play() continues, reverse() turns it around, finish() jumps to the end, and cancel() removes its effect.
⚡ Waiting for the end
Write:
await entry.finished; // carry on only after its 200 ms entry has ended
Meaning: finished is a Promise (an object that stands for a result that only exists later) that settles as soon as the animation ends. await waits for that Promise before the next line runs. This is more accurate than setTimeout, which doesn't know when the animation is paused. If the animation is cancelled with cancel(), the Promise rejects with an AbortError, so wrap it in try/catch.
⚡ fill: 'forwards' wins
Guess first: the toast enters with fill: 'forwards' (its end state is held), then other code writes toast.style.opacity = '0'. Does the toast disappear?
No. The animation stays attached to the element and beats inline styles (toast.style), so its opacity stays 1.
Meaning: So that the end state isn't locked, put the end state in CSS and animate without fill. Or use commitStyles() (writes the end result into the inline style) then cancel() (releases the animation).