DOM Animations
JavaScript can animate three ways: trigger CSS transitions via class swaps, define @keyframes from JS, or run frame-by-frame with the Web Animations API and requestAnimationFrame.
Trigger CSS transitions
CSS + JS
/* CSS */
.box { transition: transform 0.3s ease; }
.box.hover { transform: translateY(-4px); }
/* JS */
box.classList.toggle("hover");
Web Animations API (WAAPI)
JS
const anim = box.animate(
[
{ transform: "translateY(0)", opacity: 1 },
{ transform: "translateY(20px)", opacity: 0 },
],
{ duration: 300, easing: "ease-out", fill: "forwards" },
);
anim.onfinish = () => box.remove();
anim.pause(); anim.play(); anim.reverse();
anim.cancel();
requestAnimationFrame — manual loop
JS
function tick(now) {
// move things based on `now` (high-resolution timestamp ms)
draw(now);
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
// Stop with cancelAnimationFrame(id)
What to use when
| Need | Reach for |
|---|---|
| One-shot UI transition | CSS class toggle. |
| Imperative dynamic animations | WAAPI .animate(…). |
| Games / physics | requestAnimationFrame. |
| Respect "reduce motion" | Check matchMedia("(prefers-reduced-motion: reduce)").matches. |
Tip: Animate only
transform and opacity in hot paths. Other properties trigger layout or paint, which kills frame rate.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from DOM Animations!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Animate using the modern Web Animations API.
box.
([{ opacity: 0 }, { opacity: 1 }], { duration: 300 });
Seven letters.
Discussion
Loading…