Clean β’ Professional
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.
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:
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:
classList toggling for multiple elements.position: relative or absolute in CSS.left, top, opacity, transform, width, and height.transform and opacity for smoother GPU-accelerated animations.setInterval delays, transition-duration, or JavaScript easing functions.