JavaScript Element animate() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.animate() is an instance method and a shortcut for the Web Animations API. It creates an Animation, applies it to the element, plays it, and returns the instance. Learn keyframes, timing options, implicit start/end states, and five try-it labs.

01

Kind

Instance method

02

Creates

Animation

03

Plays

Immediately

04

Returns

Animation

05

Args

keyframes, options

06

Status

Baseline widely

Introduction

CSS @keyframes define motion in stylesheets. animate() does the same idea from JavaScript: pass keyframes and timing, and the browser starts playing right away.

Because it returns an Animation object, you can pause, cancel, reverse, or await animation.finished when the run completes—handy for UI feedback and sequenced motion.

💡
Beginner tip

Think of animate() as “create + play in one call.” Save the return value when you need control; ignore it for fire-and-forget effects.

This page is part of JavaScript Element. Related topics include after() and the JavaScript hub.

Understanding the animate() Method

Calling el.animate(keyframes, options) builds a keyframe effect on el, starts playback, and hands back the live Animation.

  • It is an instance method on Element (Animatable).
  • Keyframes describe property values over time (array or object form).
  • Options set duration, iterations, easing, fill, and more—or a plain duration number.
  • Elements may run multiple animations; list them with getAnimations().
  • Optional advanced fields: id, timeline, rangeStart, rangeEnd.

📝 Syntax

General form of Element.animate (MDN):

JavaScript
animate(keyframes, options)

Parameters

  • keyframes — an array of keyframe objects, or a keyframe object whose properties are arrays of values to iterate over.
  • options — either an integer duration in milliseconds, or an object with timing properties (and optional id, timeline, rangeStart, rangeEnd).

Common timing options

  • duration — length of one iteration (ms).
  • iterations — how many times to repeat (Infinity allowed).
  • easing — timing function (for example "ease-in-out").
  • delay — wait before starting (ms).
  • direction"normal", "reverse", "alternate", …
  • fill — how styles persist before/after ("none", "forwards", "both", …).
  • id — string name unique to animate() for referencing the animation.

Return value

Returns an Animation object instance.

Common patterns

JavaScript
el.animate(
  [{ opacity: 0 }, { opacity: 1 }],
  { duration: 400, easing: "ease-out" }
);

// Duration-only shorthand
el.animate({ transform: "translateX(40px)" }, 500);

const anim = el.animate(keyframes, options);
anim.pause();
await anim.finished;

⚡ Quick Reference

GoalCode
Play a keyframe animationel.animate(keyframes, options)
Duration onlyel.animate(keyframes, 1000)
Loop forever{ iterations: Infinity }
Keep end styles{ fill: "forwards" }
Control playbackanim.pause() / anim.cancel()
List animations on elel.getAnimations()
MDN statusBaseline Widely available (since March 2020)

🔍 At a Glance

Four facts to remember about Element.animate().

Returns
Animation

Live playback handle

Baseline
widely

Since March 2020

Starts
auto-play

Creates and plays

API
Web Animations

JS keyframe motion

📋 animate() vs CSS @keyframes

el.animate(...)CSS animation / @keyframes
Defined inJavaScriptStylesheet
StartsOn the method callWhen the class/rule applies
Control handleReturned AnimationClasses / animation-play-state
Dynamic valuesEasy (variables in JS)Often needs custom properties
Best forInteractive / sequenced UIDeclarative, reusable styles

Examples Gallery

Examples follow MDN Element.animate() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Rotate/scale on click, and run an infinite translate—core MDN demos.

Example 1 — Rotating and Scaling (MDN)

On click, spin and shrink an element with an array of keyframes.

JavaScript
const newspaperSpinning = [
  { transform: "rotate(0) scale(1)" },
  { transform: "rotate(360deg) scale(0)" },
];

const newspaperTiming = {
  duration: 2000,
  iterations: 1,
};

const newspaper = document.querySelector(".newspaper");

newspaper.addEventListener("click", () => {
  newspaper.animate(newspaperSpinning, newspaperTiming);
});
Try It Yourself

How It Works

Each click creates and plays a new animation from full size/rotation to scaled-away. The method returns an Animation (unused here for a fire-and-forget effect).

Example 2 — Infinite Loop (MDN Tunnel Style)

Translate forever with iterations: Infinity.

JavaScript
document.getElementById("tunnel").animate(
  [
    { transform: "translateY(0px)" },
    { transform: "translateY(-300px)" },
  ],
  {
    duration: 1000,
    iterations: Infinity,
  },
);
Try It Yourself

How It Works

One second per cycle, forever. Call animation.cancel() (or remove the element) when you want the motion to stop.

📈 Practical Patterns

Implicit keyframes, fades with fill, and controlling the returned Animation.

Example 3 — Implicit To/From Keyframes (MDN)

One keyframe can be the end state; the browser fills the start from current style.

JavaScript
const logo = document.getElementById("logo");

// Single keyframe = end state; start inferred from current style
logo.animate({ transform: "translateX(300px)" }, 1000);

// offset: 0 → provided keyframe is the start; end inferred
logo.animate({ transform: "translateX(300px)", offset: 0 }, 1000);
Try It Yourself

How It Works

With a single frame and no offset, that frame is treated as the end. Set offset: 0 to treat it as the start instead.

Example 4 — Fade In with fill: "forwards"

Object-form keyframes and keep the final opacity after the animation ends.

JavaScript
const card = document.getElementById("card");

card.animate(
  {
    opacity: [0, 1],
    transform: ["translateY(12px)", "translateY(0)"],
  },
  {
    duration: 600,
    easing: "ease-out",
    fill: "forwards",
  },
);
Try It Yourself

How It Works

Object form uses property arrays. Without fill: "forwards", styles often snap back when the animation finishes.

Example 5 — Pause, Play, and Cancel

Keep the returned Animation to control playback.

JavaScript
const box = document.getElementById("box");
const anim = box.animate(
  [
    { transform: "translateX(0)" },
    { transform: "translateX(120px)" },
  ],
  { duration: 2000, iterations: Infinity, direction: "alternate" },
);

document.getElementById("pause").onclick = () => anim.pause();
document.getElementById("play").onclick = () => anim.play();
document.getElementById("stop").onclick = () => anim.cancel();
Try It Yourself

How It Works

play(), pause(), and cancel() operate on the same Animation instance returned by animate().

🚀 Common Use Cases

  • Click feedback: scale, shake, or spin a button or card.
  • Enter/exit transitions for dialogs, toasts, and list items.
  • Loading indicators that loop until you cancel().
  • Sequencing motion with await animation.finished.
  • Dynamic motion when values come from JS (distance, color, delay).
  • Teaching Web Animations alongside CSS @keyframes.

🧠 How animate() Runs

1

Pass keyframes + options

Describe property values over time and timing (or a duration number).

Input
2

Create an Animation

The browser builds the effect and attaches it to the element.

Create
3

Play automatically

Playback starts immediately—no extra play() needed.

Play
4

Return the Animation

Pause, cancel, or await finished when you need control.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available since March 2020).
  • Some options (timeline, rangeStart, rangeEnd) have narrower support—check compatibility when using scroll/view timelines.
  • Prefer animating transform and opacity for smoother performance.
  • Use fill: "forwards" when the end visual state must remain.
  • Related: after(), children, JavaScript hub.

Browser Support

Element.animate() is Baseline Widely available (MDN: across browsers since March 2020). Logos use the shared browser-image-sprite.png sprite from this project. Advanced timeline range options may vary.

Baseline Widely available

Element.animate()

Safe for production keyframe animations. Keep a reference to pause, cancel, or await finished.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Not supported · Use CSS or a polyfill
No
animate() Excellent

Bottom line: Use animate() for JS-driven motion. Prefer transform/opacity. Check support before relying on ViewTimeline ranges.

Conclusion

Element.animate() creates and plays a Web Animations API animation in one call, returning an Animation you can control. Pass keyframes plus timing (or a duration number) and prefer transform / opacity for smooth UI motion.

Continue with after(), children, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Animate transform and opacity when possible
  • Save the returned Animation for pause/cancel
  • Use fill: "forwards" when end styles must stick
  • Prefer await anim.finished for sequences
  • Cancel infinite loops when the UI no longer needs them

❌ Don’t

  • Animate layout thrashing properties casually (width/top)
  • Forget that some timeline-range options need newer browsers
  • Leak infinite animations on removed elements
  • Expect IE to support animate()
  • Confuse CSS class toggles with the returned Animation API

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.animate()

Create + play keyframe animations from JavaScript in one call.

5
Core concepts
🎬 02

Creates

+ plays

Shortcut
⏱️ 03

Options

or duration ms

Timing
04

Baseline

widely available

Status
05

Prefer

transform/opacity

Perf

❓ Frequently Asked Questions

It is a Web Animations API shortcut: it creates a new Animation, applies it to the element, plays it, and returns the Animation object so you can pause, cancel, or await finish.
No. MDN marks Element.animate() as Baseline Widely available (across browsers since March 2020). It is not Deprecated, Experimental, or Non-standard. Some options like scroll timeline ranges may have narrower support.
An Animation instance. Keep the reference if you need play(), pause(), cancel(), finished, or playbackRate.
Yes. Passing a number is treated as duration in milliseconds — for example el.animate(keyframes, 1000).
Yes. You can call animate() several times. Use Element.getAnimations() to list animations that currently affect the element.
CSS animations are declarative in stylesheets. animate() creates the same kind of animation from JavaScript with a returned Animation you can control in code.
Did you know?

One element can run several animations at once. Call element.getAnimations() to inspect or cancel everything currently affecting that node—useful when stacking hover, click, and enter effects.

More Element Topics

Browse Element methods and properties to keep building DOM skills.

after() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful