Element.animate Runs Keyframe Animations

animate() starts a Web Animation immediately, returning an Animation object whose playState, currentTime, and finished promise give full programmatic control.

JavascriptData Integrity

Code

javascriptsnippet
29 lines
// Web Animations API: animate() returns an Animation object you control.
const card = document.createElement('div');
document.body.append(card);

const animation = card.animate(
  [
    { transform: 'translateY(0)', opacity: 1 },
    { transform: 'translateY(-8px)', opacity: 0.6 },
    { transform: 'translateY(0)', opacity: 1 },
  ],
  { duration: 400, easing: 'ease-in-out', iterations: 2 }
);

console.log('running :', animation.playState); // 'running' immediately
animation.pause();
console.log('paused  :', animation.playState);
animation.play();

// finish() jumps to the very end: currentTime equals the full active duration.
animation.finish();
console.log('finished:', animation.playState, 'currentTime:', animation.currentTime);

// animation.finished is a promise; cancel() rejects it with an AbortError.
animation.cancel();
try {
  await animation.finished;
} catch (rejection) {
  console.log('rejected:', rejection.name);
}

How the snippet works

Every asynchronous step is awaited, so rejections surface where the call happens.

The demo data lives in module-level bindings: card, animation.

Watch out for

  • The environment needs no preparation beyond having the interpreter or compiler.
  • Uses document, so it needs a browser context — it will not run as-is in Node without shims.

Applying it

Each run prints the 4 labeled blocks running :, paused :, finished:, rejected: in source order.

Statements that matter

await animation.finished;

Interactive Tools for This Topic

FAQ

Does Element.animate Runs Keyframe Animations run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.