iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

NeedReach for
One-shot UI transitionCSS class toggle.
Imperative dynamic animationsWAAPI .animate(…).
Games / physicsrequestAnimationFrame.
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 });

Test yourself

Q1. Modern programmatic animation API is…
Q2. Cheapest properties to animate at 60fps are…
Q3. Respect users who prefer reduced motion via…

Discussion

Loading…