JavaScript can be used to create dynamic animations by gradually changing the style of an element over a sequence of tiny time intervals. This allows for movement, fades, and smooth transitions.
To create a basic movement, you typically need a container element and a moving element. The
container must have position: relative, and the moving
element must have position: absolute.
The setInterval() method calls a function at specified intervals. By changing a
property (like top or left) by 1px every 5 milliseconds, you
create the illusion of smooth movement.
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
For modern, professional web development, requestAnimationFrame()
is the preferred choice. It tells the browser that you wish to perform an animation and
requests that the browser calls a specified function to update an animation before the next
repaint.
top, left, or
transform to define position.position: absolute is essential for coordinate-based movementsetInterval() is simple but less efficient for logic-heavy
motionrequestAnimationFrame() is the gold standard for web
performanceclearInterval()) to
prevent memory leaks