Tutorials

The Web Animations API: a practical guide to element.animate()

A practical Web Animations API guide: animate(), play, pause, reverse, finished, playbackRate, composite, fill, commitStyles and converting CSS keyframes.

· 6 min read

The Web Animations API (WAAPI) is the browser's own animation engine, exposed to JavaScript. CSS animations and transitions run on it too; WAAPI just lets you create and steer the same kind of animation from a script. You get keyframes, duration, delay and easing, plus play, pause, reverse, seeking, speed control and a promise that resolves when the animation ends. No library, no download.

This guide covers element.animate(), the Animation object, fill and commitStyles(), composite modes, getAnimations(), and how to turn a CSS @keyframes rule into WAAPI without changing how it feels.

currentTime 0 ms · playbackRate 1 · idle

Reduced motion is on, so the demo waits for you to press Play.

Two animations, one set of controls via getAnimations()

How the demo is put together

PartPropertyDurationDelayEasing
Runnertransform: translateX(0 → 100% - 28px)1600 ms0cubic-bezier(.65, 0, .35, 1)
Dotrotate(0 → 180deg), border-radius: 8px → 50%1600 ms0cubic-bezier(.65, 0, .35, 1)
Controlsplay(), pause(), reverse(), updatePlaybackRate()instant0none

The buttons never reference the two animations directly. They call track.getAnimations({ subtree: true }) once and send every command to the whole list, which keeps the runner and the dot in step.

element.animate(keyframes, options)

One call creates an animation and starts it:

const card = document.querySelector('.card');

const anim = card.animate(
  [
    { opacity: 0, transform: 'translateY(16px)' },
    { opacity: 1, transform: 'translateY(0)' }
  ],
  {
    duration: 400,          // milliseconds, not seconds
    delay: 100,
    easing: 'cubic-bezier(.2, .8, .2, 1)',
    fill: 'both',
    iterations: 1           // Infinity for a loop, not 'infinite'
  }
);

Keyframes are an array of objects with camelCase property names (backgroundColor, not background-color). A keyframe can carry its own offset (0 to 1, the equivalent of a CSS percentage) and its own easing. You can also pass a single object of arrays, { opacity: [0, 1] }, which is handy for short animations.

The options mirror the CSS animation-* properties:

WAAPI optionCSS equivalentNote
durationanimation-durationNumber in ms
delay, endDelayanimation-delayendDelay has no CSS equivalent
easinganimation-timing-functionDefaults to linear, not ease
iterationsanimation-iteration-countUse Infinity
directionanimation-directionSame keywords
fillanimation-fill-modeSame keywords, plus auto
compositeanimation-compositionreplace, add, accumulate
idanimation-nameAny string, useful when debugging

The Animation object

element.animate() returns an Animation. This is where WAAPI earns its place over plain CSS:

anim.pause();
anim.play();
anim.reverse();               // flips direction and plays
anim.finish();                // jump to the end
anim.cancel();                // remove all effects, back to the original style

anim.currentTime = 200;       // seek, in ms
anim.updatePlaybackRate(2);   // twice as fast, without a jump
anim.playState;               // 'idle' | 'running' | 'paused' | 'finished'

await anim.finished;          // resolves when the animation ends

finished is a promise, so sequencing is plain async code. It rejects if the animation is cancelled, so wrap it when that can happen:

async function closePanel(panel) {
  const anim = panel.animate(
    [{ opacity: 1, transform: 'scale(1)' }, { opacity: 0, transform: 'scale(.96)' }],
    { duration: 180, easing: 'cubic-bezier(.4, 0, 1, 1)' }
  );
  try {
    await anim.finished;
    panel.hidden = true;
  } catch {
    // cancelled, leave the panel visible
  }
}

Prefer updatePlaybackRate() to setting playbackRate directly while an animation runs. It waits until the change can be applied in sync with any compositor-driven playback, so there is no visible jump.

fill and commitStyles()

When an animation ends, its effect is removed and the element snaps back to its normal style. fill: 'forwards' keeps the final frame, but it does so by keeping the animation alive, overriding the element's style indefinitely. Filling animations pile up, and the browser automatically removes ones that are fully replaced by newer animations, which can surprise you if you kept a reference.

The cleaner pattern is to write the end state into the element's inline style and then cancel the animation:

const anim = box.animate(
  { transform: 'translateX(240px)' },
  { duration: 300, easing: 'ease-out', fill: 'forwards' }
);
await anim.finished;
anim.commitStyles();   // writes transform: translateX(240px) into style=""
anim.cancel();         // the animation is gone, the style stays

Notice the single keyframe. When you give only the end state, the browser uses the element's current value as the start, the same way a CSS transition does.

Composite modes

By default an animation replaces the property's value. composite: 'add' layers it on top instead, so two animations on transform can combine rather than fight:

// a hover lift that is already applied in CSS: transform: translateY(-4px)
icon.animate(
  [{ transform: 'scale(1)' }, { transform: 'scale(1.15)' }, { transform: 'scale(1)' }],
  { duration: 300, composite: 'add' }
);
// result during the pulse: translateY(-4px) scale(1.15)

add appends transform functions to the list. accumulate merges matching functions numerically: scale(1.1) accumulated onto scale(1.1) gives scale(1.2), while add gives scale(1.1) scale(1.1), which is 1.21. For opacity and lengths both modes simply sum the values.

getAnimations()

document.getAnimations() returns every running animation on the page, and element.getAnimations() those on one element (add { subtree: true } for its children). The list includes CSS animations and CSS transitions as well as script-made ones, so you can pause or wait for CSS motion from JavaScript:

// slow every animation on the page to 10% speed while debugging
document.getAnimations().forEach(a => a.updatePlaybackRate(0.1));

// wait until a CSS transition on a dialog has finished
await Promise.all(dialog.getAnimations().map(a => a.finished));

Animations from getAnimations() that came from CSS are CSSAnimation and CSSTransition objects, with an animationName or transitionProperty you can filter on.

Converting CSS @keyframes to WAAPI

Here is a toast entrance in CSS:

@keyframes toast-in {
  0%   { opacity: 0; transform: translateY(12px) scale(.96); }
  60%  { opacity: 1; transform: translateY(-2px) scale(1.01); }
  100% { opacity: 1; transform: none; }
}
.toast { animation: toast-in 420ms cubic-bezier(.2, .8, .2, 1) 80ms both; }

And the same motion in WAAPI:

const ease = 'cubic-bezier(.2, .8, .2, 1)';
toast.animate(
  [
    { offset: 0,  opacity: 0, transform: 'translateY(12px) scale(.96)', easing: ease },
    { offset: .6, opacity: 1, transform: 'translateY(-2px) scale(1.01)', easing: ease },
    { offset: 1,  opacity: 1, transform: 'none' }
  ],
  { duration: 420, delay: 80, fill: 'both' }
);

The easing sits on each keyframe, not in the options, and that is deliberate. In CSS, animation-timing-function applies to each segment between keyframes. In WAAPI, the easing option applies once across the whole iteration, and per-keyframe easing applies to each segment. Put the curve in the options and the toast would ease once over 420 ms instead of twice, and feel noticeably different. Seconds become milliseconds, percentages become offsets, and infinite becomes Infinity.

If the easing curve is the part you are unsure of, the CSS easing functions guide covers how each keyword and cubic-bezier() behaves. The same strings work in WAAPI.

Respecting reduced motion

A CSS @media (prefers-reduced-motion: reduce) block does not stop animations created in script. Check the setting yourself:

const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
el.animate(keyframes, { duration: reduce ? 0 : 400, fill: 'both' });

A duration of zero jumps straight to the end state, so the interface still updates. The reduced motion guide goes into which animations to keep, soften or remove.

WAAPI, CSS or a library?

Debugging in DevTools

Animations created with element.animate() appear in Chrome's Animations panel next to CSS animations and transitions, so you can scrub, replay and slow them down. Setting an id gives each one a readable label there and in getAnimations(). The DevTools inspection guide walks through the panel step by step.

If you want the numbers out of an animation you have seen on another site, Capture Motion records it while it plays and reads the keyframes, durations, delays and easing of every animated property. It reads WAAPI, CSS, GSAP and Lottie animations the same way, and exports CSS, React or GSAP code, or JSON you can rebuild in WAAPI with the pattern above.

Questions

Is the Web Animations API supported in all browsers?

The core of it, element.animate() and the Animation object with play, pause, reverse and finished, works in all current major browsers. Newer parts such as composite modes and commitStyles() arrived later, so check caniuse if you need to support older versions.

Why does my converted CSS animation feel different in WAAPI?

Usually two things: WAAPI defaults to linear easing where CSS defaults to ease, and the easing option applies to the whole iteration, while CSS applies its timing function between each pair of keyframes. Put the easing on each keyframe to match CSS exactly.

Does the Web Animations API run on the compositor?

Animations of transform and opacity created with element.animate() can run off the main thread in the same way as CSS animations, so they stay smooth while JavaScript is busy. Animating layout properties such as width or top does not get that benefit.

Can I copy a Web Animations API animation from another site?

Yes. Capture Motion records the animation while it plays and reads its keyframes, duration, delay and easing, whether it was made with WAAPI, CSS, GSAP or Lottie, then exports it as CSS, React, GSAP or JSON.