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.
Code
// 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
Cubic Bezier PreviewPreview a CSS cubic-bezier() easing curve, validate the control points, and sample the progress mapping from input to output value.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.