Dom Animations in JavaScript
? DOM Animations in JavaScript
Animating elements on a webpage can make your UI more engaging and interactive. In JavaScript, you can create animations by manipulating the DOM (Document Object Model) over time.
Ways to Animate DOM Elements in JavaScript
1. Using setInterval or setTimeout
2. Using requestAnimationFrame (preferred for smooth animations)
3. Using CSS animations triggered by JavaScript
? 1. Basic Animation with setInterval
<div id="box" style="width:50px; height:50px; background:red; position:absolute;"></div><script>let pos = 0;const box = document.getElementById("box");const interval = setInterval(() => { if (pos >= 300) { clearInterval(interval); } else { pos++; box.style.left = pos + "px"; // Move right by 1px every 10ms }}, 10);</script>? 2. Smooth Animation with requestAnimationFrame
requestAnimationFrame lets the browser optimize animation for smoothness and efficiency.
<div id="circle" style="width:50px; height:50px; background:blue; border-radius:50%; position:absolute;"></div><script>const circle = document.getElementById("circle");let position = 0;function animate() { if (position < 300) { position++; circle.style.top = position + "px"; circle.style.left = position + "px"; requestAnimationFrame(animate); }}animate(); // Start animation</script>? 3. Trigger CSS Animation with JavaScript
CSS:
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; }}.fade-in { animation: fadeIn 2s forwards;}HTML + JS:
<div id="text" style="opacity: 0;">Hello World!</div><script>document.getElementById("text").classList.add("fade-in");</script>Tips for DOM Animations
Use
requestAnimationFrameinstead ofsetIntervalfor better performance.Avoid animating properties that trigger layout recalculation (like
width,height,top), and prefer transform and opacity for smoother animations.Consider using CSS transitions/animations for simple effects triggered by JS.
Would you like me to show you a full example of a complex animation, or how to animate with GSAP (a popular JS animation library)?