Styles, Classes, and Layout via JavaScriptLesson 3.4
CSS transitions vs JavaScript animation: requestAnimationFrame
CSS transition, requestAnimationFrame, animation loop, cancelAnimationFrame, performance, reflow avoidance
CSS Transitions vs requestAnimationFrame
For state-change animations (open/close, hover effects), CSS transitions are the right tool — they run on the compositor thread without touching JavaScript.
/* CSS */
.panel { height: 0; overflow: hidden; transition: height 0.3s ease; }
.panel.open { height: 200px; }
/* JS — just toggle the class */
btn.addEventListener('click', () => panel.classList.toggle('open'));requestAnimationFrame for JavaScript-Driven Animation
When animation logic must live in JavaScript (physics, canvas, data-driven), use requestAnimationFrame. The browser calls your callback once per frame just before painting — synced to the display refresh rate.
let x = 0;
let animId;
function animate() {
x += 2;
box.style.transform = `translateX(${x}px)`;
if (x < 300) animId = requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// Stop it:
cancelAnimationFrame(animId);Never use setInterval for animation — it ignores the frame budget and causes jank. Batch all DOM reads before writes inside a single frame to avoid forced reflows.
