DOM Animations
A DOM animation is a change to an element's appearance spread over time, such as a row fading in, a panel sliding open or a progress bar filling up. JavaScript has three ways to animate, from simplest to most flexible: toggle a class and let a CSS transition do the work; drive frame-by-frame changes with requestAnimationFrame; or use the Web Animations API (element.animate), which gives CSS-quality animations with JavaScript control. Whatever you choose, respect people who have asked their system to reduce motion.
In One Minute
- Simplest and best for most cases: define a CSS
transition, then add or remove a class with JavaScript. requestAnimationFrame(callback)runs your function just before the next screen repaint, about 60 times a second. Use it for custom frame-by-frame animation.element.animate(keyframes, options)(Web Animations API) runs an animation and returns an object you can pause, reverse andawait(animation.finished).- Animate
transformandopacity; they are cheap. Animatingwidth,heightortopforces layout work every frame. - Check
matchMedia("(prefers-reduced-motion: reduce)")and shorten or skip motion when it matches.
CSS Transitions Triggered by JavaScript
A CSS transition animates a property smoothly whenever its value changes. JavaScript only changes the value, usually by toggling a class:
<style>
.panel { opacity: 0; transform: translateY(-8px); transition: opacity 150ms, transform 150ms; }
.panel.open { opacity: 1; transform: none; }
</style>
<button id="toggle">Show details</button>
<div class="panel" id="details">Tuition $400, books $85</div>
<script>
const panel = document.querySelector("#details");
document.querySelector("#toggle").addEventListener("click", () => {
panel.classList.toggle("open");
});
panel.addEventListener("transitionend", (event) => {
console.log(`transition of ${event.propertyName} ended, opacity ${getComputedStyle(panel).opacity}`);
});
</script>transition of opacity ended, opacity 1
transition of transform ended, opacity 1Explanation: clicking the button adds the open class; the browser animates opacity and transform over 150 milliseconds; each property fires a transitionend event when it finishes. All the timing and easing lives in CSS, where designers can adjust it, and the browser can run it efficiently.
requestAnimationFrame
requestAnimationFrame(callback) asks the browser to call your function right before it paints the next frame. The callback receives a high-resolution timestamp. To animate, compute the state for the current time and request the next frame:
<div id="bar" style="height: 8px; background: seagreen; width: 0"></div>
<script>
const bar = document.querySelector("#bar");
const duration = 200;
let start = null;
let frames = 0;
function step(now) {
start ??= now;
frames++;
const progress = Math.min((now - start) / duration, 1);
bar.style.width = `${progress * 100}%`;
if (progress < 1) {
requestAnimationFrame(step);
} else {
console.log(`done: width ${bar.style.width}, more than 5 frames: ${frames > 5}`);
}
}
requestAnimationFrame(step);
</script>done: width 100%, more than 5 frames: trueExplanation: progress is computed from elapsed time, not from counting frames, so the animation takes 200 ms whether the screen runs at 60, 120 or 30 frames per second. The exact number of frames varies by machine, so the example only checks that there were several.
requestAnimationFrame | setInterval(fn, 16) |
|---|---|
| Synced with the screen's refresh | Fires on its own schedule, causing jank |
| Pauses in background tabs (saves battery) | Keeps running in background tabs |
| Receives a precise timestamp | You must read the clock yourself |
cancelAnimationFrame(id) stops a pending frame; requestAnimationFrame returns that id.
The Web Animations API
element.animate(keyframes, options) runs a CSS-quality animation defined in JavaScript. It returns an Animation object with controls and a finished promise:
<p id="saved">Payment saved</p>
<script>
const saved = document.querySelector("#saved");
const animation = saved.animate(
[
{ opacity: 0, transform: "scale(0.95)" },
{ opacity: 1, transform: "scale(1)" },
],
{ duration: 150, easing: "ease-out", fill: "forwards" }
);
console.log(animation.playState);
animation.finished.then(() => {
console.log(animation.playState, getComputedStyle(saved).opacity);
});
</script>running
finished 1| Option | Meaning |
|---|---|
duration | Length in milliseconds |
easing | "linear", "ease-in", "ease-out", "ease-in-out", or a cubic-bezier(...) |
delay | Wait before starting |
iterations | How many times (Infinity to loop) |
direction | "normal", "reverse", "alternate" |
fill | "forwards" keeps the final state after it ends |
| Animation method or property | Does |
|---|---|
pause(), play(), reverse(), cancel(), finish() | Controls playback |
playbackRate | Speed (2 is double speed) |
currentTime | Position in milliseconds |
finished | A promise that resolves when it ends |
The finished promise makes it easy to run steps in sequence, such as "fade out, then remove the element", which is awkward with CSS alone. (Promises are explained fully in the async chapter.)
Respecting Reduced Motion
Some people get dizzy or nauseous from motion on screen and turn on "Reduce motion" in their operating system settings. Pages can detect it with the media query prefers-reduced-motion:
<p id="msg">Saved</p>
<script>
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
function showSaved(el) {
const duration = reduceMotion.matches ? 0 : 150;
return el.animate([{ opacity: 0 }, { opacity: 1 }], { duration, fill: "forwards" });
}
console.log("reduce motion:", reduceMotion.matches);
showSaved(document.querySelector("#msg"));
</script>reduce motion: falseThe checker's browser has no reduced-motion preference, so matches is false. In CSS, the same check is @media (prefers-reduced-motion: reduce) { ... }. Reduce or remove movement (sliding, zooming, parallax) for these readers; simple fades are generally fine.
In Practice
The Fee Tracker removes a canceled payment row smoothly: fade and slide it out with the Web Animations API, then remove it from the DOM, skipping the motion for readers who asked for less:
<ul id="rows">
<li>Navika $120 <button>Cancel</button></li>
<li>Advitha $45 <button>Cancel</button></li>
</ul>
<script>
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
const rows = document.querySelector("#rows");
rows.addEventListener("click", async (event) => {
const row = event.target.closest("li");
if (!event.target.matches("button") || !row) return;
await row.animate(
[{ opacity: 1, transform: "none" }, { opacity: 0, transform: "translateX(24px)" }],
{ duration: reduce ? 0 : 150, easing: "ease-in" }
).finished;
row.remove();
console.log(`${rows.children.length} row left: ${rows.textContent.trim()}`);
});
</script>1 row left: Advitha $45 Cancelawait pauses the click handler until the animation's finished promise resolves, so the row is removed only after it has faded out.
Common Mistakes
Using setInterval for animation. It isn't synced with the screen. Use requestAnimationFrame or element.animate.
Advancing by a fixed amount per frame. Faster screens animate faster. Compute progress from elapsed time.
Animating layout properties. width, height and top are expensive. Animate transform and opacity.
Ignoring reduced motion. Check prefers-reduced-motion and shorten or skip motion.
Practice
Challenge: Make a "highlight" effect: when the button is clicked, animate the paragraph's background from yellow to transparent over 200 ms, then log "highlight done".
Show solution
<p id="note">Balance updated</p>
<button id="go">Highlight</button>
<script>
document.querySelector("#go").addEventListener("click", async () => {
const note = document.querySelector("#note");
await note.animate([{ backgroundColor: "yellow" }, { backgroundColor: "transparent" }], { duration: 200 }).finished;
console.log("highlight done");
});
</script>highlight doneKey Takeaways
| Need | Use |
|---|---|
| Simple state change | Class toggle plus CSS transition |
| Custom per-frame drawing | requestAnimationFrame |
| Controllable animation | el.animate(keyframes, options) |
| Do something after | await animation.finished |
| Reduced motion | matchMedia("(prefers-reduced-motion: reduce)") |
Was this tutorial helpful?