DOM Animations
In the HTML DOM, JavaScript can create animations by dynamically changing the properties of HTML elements over time. Animations enhance user experience by making web pages feel interactive, lively, and responsive. They can be simple, like moving an element, or complex, like fading, scaling, or chaining multiple effects.
Ways to Animate with JavaScript
Using setInterval()
or setTimeout()
You can update element styles repeatedly over time to create basic animations.
Example: Moving a Box Horizontally
const box = document.getElementById("box");
let position = 0;
const interval = setInterval(() => {
if(position >= 300) {
clearInterval(interval); // Stop animation
} else {
position += 5;
box.style.left = position + "px"; // Update position
}
}, 20); // Runs every 20ms
Using requestAnimationFrame()
requestAnimationFrame()
is a modern, efficient method for smoother animations, as it syncs with the browser's refresh rate.
Example: Smooth Movement
const box = document.getElementById("box");
let pos = 0;
function animate() {
if(pos < 300) {
pos += 2;
box.style.left = pos + "px";
requestAnimationFrame(animate); // Recursively call
}
}
animate();
Advantages over setInterval
:
- Optimized for performance.
- Avoids unnecessary CPU usage.
- Produces smoother animations.
CSS Animations Controlled by JS
JavaScript can add/remove classes that have CSS animations or transitions defined. This is easier for complex animations.
Example: Fade In Using CSS & JS
.fade {
opacity: 0;
transition: opacity 1s ease-in-out;
}
.fade.show {
opacity: 1;
}
const element = document.getElementById("myElement");
element.classList.add("show"); // Triggers fade-in animation
Advantages:
- Leverages GPU for better performance.
- Easier to maintain for complex animations.
- Works well with
classList
toggling for multiple elements.
Key Concepts for DOM Animations
- Element Positioning: Animations often require
position: relative
orabsolute
in CSS. - Property Updates: Commonly animated properties include
left
,top
,opacity
,transform
,width
, andheight
. - Performance Considerations: Use
transform
andopacity
for smoother GPU-accelerated animations. - Timing & Easing: Control speed with
setInterval
delays,transition-duration
, or JavaScript easing functions.