Skip to content
jshacks.dev
Browser

JavaScript element.animate(): The Web Animations API

How element.animate() runs keyframe animations from JavaScript: timing options, the finished promise, pause and reverse, commitStyles() and reduced motion.

7 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome, NGINX and Postman logos.

CSS transitions and animations cover most motion on a page, and they are the right choice when the motion is known in advance and tied to a state change. They are awkward when the start value is computed, when a script needs to know the moment an animation ends, or when you want to pause, reverse or speed up one that is running. The Web Animations API puts the same engine behind a JavaScript interface, and element.animate() is its entry point. It takes a list of keyframes and timing options, starts an animation on the compositor when it can, and returns an Animation object with a promise, playback controls and a current time. This post explains how element.animate() works in JavaScript: the keyframe formats, the timing options, the Animation object and its finished promise, how to pause, reverse and scrub, how to chain animations, how to commit the final state, the effect of reduced-motion settings, and the limits. It is specified in Web Animations, documented on MDN, and supported in all current browsers.

A first animation

animate(keyframes, options) takes an array of keyframe objects, each a set of CSS properties, and an options object or a duration in milliseconds.

basic.jsJavaScript
const box = document.createElement("div");
box.style.cssText = "width:50px;height:50px;background:teal";
document.body.append(box);

const animation = box.animate(
  [{ transform: "translateX(0)" }, { transform: "translateX(200px)" }],
  { duration: 500, easing: "ease-out" },
);

console.log(animation.playState);
console.log(animation.effect.getTiming().duration);
Text
running
500

The box slides 200 pixels to the right over half a second and then snaps back to where it started, because by default the animation leaves no lasting effect on the element after it finishes. That is the main difference from a CSS transition, which changes a property for good. The playState is running right after the call, since the animation starts at once.

Keyframe formats

Two forms are accepted. The array form lists each keyframe, and an optional offset from 0 to 1 places it in time. The object form lists the values of each property.

formats.jsJavaScript
const el = document.createElement("div");
document.body.append(el);

const a = el.animate(
  [
    { opacity: 0, offset: 0 },
    { opacity: 1, offset: 0.2 },
    { opacity: 1, offset: 0.8 },
    { opacity: 0, offset: 1 },
  ],
  1000,
);

const b = el.animate(
  { transform: ["scale(1)", "scale(1.2)", "scale(1)"], easing: "ease-in-out" },
  600,
);

console.log(a.effect.getKeyframes().length, b.effect.getKeyframes().length);
Text
4 3

If you give just one keyframe, the animation runs from the element's current computed value to that keyframe, which is how you animate from "wherever it is now" without reading the value yourself. CSS properties are written in camel case, as backgroundColor, and float is cssFloat and offset is cssOffset, since the plain names clash with keyframe properties. Custom properties can be animated too if they are registered with CSS.registerProperty(), which gives them a type the browser can interpolate.

Timing options

The second argument controls the timing. A bare number is the duration in milliseconds, and an object carries the full set.

OptionMeaningDefault
durationLength of one iteration, in ms0
delayWait before starting, in ms0
iterationsHow many times to repeat, Infinity allowed1
directionnormal, reverse, alternate, alternate-reversenormal
easinglinear, ease, cubic-bezier(...), steps(...)linear
fillnone, forwards, backwards, bothnone
endDelayWait after the end, in ms0
compositereplace, add, accumulatereplace
timing.jsJavaScript
const el = document.createElement("div");
document.body.append(el);

const pulse = el.animate([{ opacity: 1 }, { opacity: 0.3 }], {
  duration: 800,
  iterations: Infinity,
  direction: "alternate",
  easing: "ease-in-out",
});

console.log(pulse.effect.getComputedTiming().iterations);
pulse.cancel();
Text
Infinity

The fill option decides whether the first or last keyframe keeps applying outside the active time. fill: "forwards" holds the end state after the animation finishes, which is the equivalent of a transition's lasting change. Be aware that a filled animation keeps affecting the element, and it overrides the element's style, which makes later changes to that property seem to do nothing. The cleaner way to commit is shown below.

The Animation object and its promise

animate() returns an Animation. Its finished promise resolves when the animation completes and rejects with an AbortError if it is canceled, and ready resolves when it has started playing.

finished.jsJavaScript
const el = document.createElement("div");
document.body.append(el);

async function fadeOut(element) {
  const animation = element.animate([{ opacity: 1 }, { opacity: 0 }], {
    duration: 200,
    fill: "forwards",
  });

  await animation.finished;
  element.remove();
  return "removed";
}

fadeOut(el).then(console.log);
Text
removed

This is the tidy way to remove an element after it fades, with no transitionend listener and no timer that could drift from the real duration. If the animation can be canceled, handle the rejection, or the unhandled promise rejection will appear in the console.

cancel.jsJavaScript
const animation = document.body.animate({ opacity: [1, 0.5] }, 1000);

animation.finished.catch((error) => console.log(error.name));
animation.cancel();
Text
AbortError

Pause, reverse, scrub and speed

Because the animation is an object, you can control it while it runs.

control.jsJavaScript
const el = document.createElement("div");
document.body.append(el);

const animation = el.animate(
  [{ transform: "translateY(0)" }, { transform: "translateY(100px)" }],
  { duration: 1000, fill: "both" },
);

animation.pause();
animation.currentTime = 500;
console.log(animation.playState, animation.currentTime);

animation.playbackRate = 2;
animation.reverse();
console.log(animation.playbackRate);
Text
paused 500
-2

Setting currentTime jumps to that point, which is how a scroll-linked or slider-driven animation works: pause the animation and set the time from the input value. playbackRate speeds up or slows down, and a negative value plays backward, so reverse() flips the sign. updatePlaybackRate() changes the rate without a visible jump when it is playing. For scroll-linked effects there is also ScrollTimeline and ViewTimeline, which drive an animation from scroll position with no scroll handler, and which are supported in current Chromium and Safari, so feature-detect before you use them.

Committing the final state

If you want a property to stay at its final value, the options are fill: "forwards", which keeps an animation attached forever, and committing the value. The method commitStyles() writes the current animated values into the element's inline style, so you can cancel the animation and keep the result.

commit.jsJavaScript
const el = document.createElement("div");
document.body.append(el);

const animation = el.animate([{ opacity: 1 }, { opacity: 0.4 }], {
  duration: 100,
  fill: "forwards",
});

animation.finished.then(() => {
  animation.commitStyles();
  animation.cancel();
  console.log(el.style.opacity);
});
Text
0.4

This leaves the opacity as an ordinary inline style, and the finished animation no longer holds on to the element. Browsers also warn about a large number of forwards-filled animations, since they accumulate in the animation stack.

Chaining and running together

For a sequence, await each finished promise in turn. For things that run together, start them at once and wait on all of them.

sequence.jsJavaScript
async function intro(el) {
  await el.animate({ opacity: [0, 1] }, 200).finished;
  await el.animate({ transform: ["scale(0.9)", "scale(1)"] }, 200).finished;
  return "done";
}

const el = document.createElement("div");
document.body.append(el);
intro(el).then(console.log);
Text
done

document.getAnimations() and element.getAnimations() return all running animations, including CSS ones, which is handy for tools such as "wait until the page is idle" in tests.

wait.jsJavaScript
async function settle(element) {
  await Promise.all(element.getAnimations().map((a) => a.finished));
}

settle(document.body).then(() => console.log("idle"));
Text
idle

Performance

Animating transform and opacity can run on the compositor thread, off the main thread, so the motion stays smooth even when script is busy. Animating width, height, top or left forces layout on every frame and is slower. Prefer transform and opacity, and if you must animate geometry, animate a transform that produces the same visual effect. Leave will-change alone unless you have measured, since it holds memory.

Reduced motion

Some users ask their system for less motion. Respect it in script, as you would in CSS: check matchMedia("(prefers-reduced-motion: reduce)") and shorten or skip decorative animations, and keep the ones that carry meaning but make them gentle.

reduced.jsJavaScript
function animateSafely(el, keyframes, options) {
  const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
  return el.animate(keyframes, { ...options, duration: reduce ? 0 : options.duration });
}

const el = document.createElement("div");
document.body.append(el);
console.log(animateSafely(el, { opacity: [0, 1] }, { duration: 300 }).effect.getTiming().duration >= 0);
Text
true

A zero duration still fires finished, so code that waits for the animation keeps working, which is why this pattern is safer than skipping the call.

When to use CSS instead

If the motion is a state change that a class can describe, such as a hover or an open state, CSS is shorter and easier for designers to edit. If it needs computed values, runtime control, a promise, or the same keyframes applied to many elements with different delays, use the API. The two interoperate: getAnimations() lets script control CSS animations too.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.