JavaScript DOM animations let you bring pages to life by changing the style and position of HTML elements over time. By combining DOM manipulation with timers like setInterval() or browser APIs like requestAnimationFrame(), you can move, fade, rotate, and transform elements smoothly.
left, opacity, transform) repeatedly.document.getElementById() to grab elements to animate.style.left, style.opacity, etc.setInterval(), setTimeout() for repeated/delayed updates.At the core of DOM animations is a simple loop:
Using setInterval():
setInterval(callback, delay) calls callback every delay ms.clearInterval(timerId) to stop the animation.Using requestAnimationFrame():
requestAnimationFrame(fn) and do one animation step inside fn.requestAnimationFrame(fn) again from inside fn to keep it going.This example moves a red box from left to right using setInterval() and style.left.
// Simple horizontal movement using setInterval()
<div id="box" style="width:50px;height:50px;background:red;position:absolute;"></div>
<script>
let pos = 0;
// Get a reference to the box element
const box = document.getElementById("box");
// Run this function every 10ms to update the position
const timer = setInterval(() => {
// Stop when the box reaches 300px from the left
if (pos >= 300) {
clearInterval(timer);
} else {
// Increase the position and apply it to the style
pos++;
box.style.left = pos + "px";
}
}, 10);
</script>
This example slowly reduces an element’s opacity and hides it after it becomes almost transparent.
// Box that we will fade out
<div id="fadeBox" style="width:100px;height:100px;background:blue;"></div>
// Button that triggers the fadeOut() function
<button onclick="fadeOut()">Fade Out</button>
<script>
function fadeOut() {
// Get the element to fade
let el = document.getElementById("fadeBox");
// Start with full opacity (1 = fully visible)
let opacity = 1;
// Decrease the opacity every 100ms
let fade = setInterval(() => {
// If very close to invisible, stop and hide the element
if (opacity <= 0.1) {
clearInterval(fade);
el.style.display = "none";
}
// Apply the current opacity value
el.style.opacity = opacity;
// Decrease the opacity for the next step
opacity -= 0.1;
}, 100);
}
</script>
Here CSS defines a transition on transform and JavaScript simply changes the transform value to trigger a smooth rotation.
// CSS for a square box with a smooth transform transition
<style>
#box2 {
width: 100px;
height: 100px;
background: purple;
transition: transform 1s ease;
}
</style>
// Box that will be rotated
<div id="box2"></div>
// Button calls rotate() when clicked
<button onclick="rotate()">Rotate</button>
<script>
function rotate() {
// Rotate the box by 45 degrees (transition makes it smooth)
document.getElementById("box2").style.transform = "rotate(45deg)";
}
</script>
This example uses requestAnimationFrame() for a smooth green ball movement.
// Circular "ball" that will move across the screen
<div id="ball" style="width:50px;height:50px;background:green;position:absolute;border-radius:50%;"></div>
<script>
// Current x-position of the ball
let x = 0;
function animate() {
// Move until the ball reaches 300px
if (x < 300) {
// Increase position to move the ball
x += 2;
document.getElementById("ball").style.left = x + "px";
// Ask the browser to call animate() again on the next frame
requestAnimationFrame(animate);
}
}
// Start the animation
animate();
</script>
Use separate buttons to start and stop an animation by keeping the interval ID in a variable.
// Box that we will move left to right
<div id="moveBox" style="width:50px;height:50px;background:black;position:absolute;"></div>
// Buttons to start and stop the movement
<button onclick="startMove()">Start</button>
<button onclick="stopMove()">Stop</button>
<script>
// Store the interval ID so we can stop it later
let moveInt;
// Track the current position
let movePos = 0;
function startMove() {
// Create an interval that updates the position every 50ms
moveInt = setInterval(() => {
movePos += 5;
document.getElementById("moveBox").style.left = movePos + "px";
}, 50);
}
function stopMove() {
// Stop the interval so the box stops moving
clearInterval(moveInt);
}
</script>
This example moves an element in discrete steps using an array of positions and setTimeout().
// Box that jumps between fixed positions
<div id="keyBox" style="width:50px;height:50px;background:orange;position:absolute;"></div>
<script>
// Get the element and define the keyframe positions
const keyBox = document.getElementById("keyBox");
const steps = [0, 100, 200, 300];
// Index to track which step we are on
let i = 0;
function keyframe() {
// As long as there are steps left, move to the next one
if (i < steps.length) {
keyBox.style.left = steps[i] + "px";
i++;
// Wait 300ms before moving to the next step
setTimeout(keyframe, 300);
}
}
// Start the keyframe animation
keyframe();
</script>
pos increases until it reaches 300px.display: none.When you copy these snippets into a full HTML page and open it in a browser, each example will animate the corresponding element as described above.
Below is a small playground that combines the ideas above. Click Start to move the box, and Reset to bring it back. This is an “example of the examples” so you can see a complete, real animation in one place.
// Area that contains the moving box
<div id="demoArea" style="position:relative;height:80px;border:1px dashed #cbd5f5;overflow:hidden;">
<div id="demoBox" style="width:40px;height:40px;background:#ef4444;position:absolute;top:20px;left:0;"></div>
</div>
// Buttons to start and reset the animation
<button id="demoStart">Start</button>
<button id="demoReset">Reset</button>
<script>
// Get references to the elements we need
const demoBox = document.getElementById("demoBox");
const demoArea = document.getElementById("demoArea");
const demoStart = document.getElementById("demoStart");
const demoReset = document.getElementById("demoReset");
// Current x-position of the demo box
let demoX = 0;
// Flag to know if the animation is currently running
let demoAnimating = false;
function step() {
// If animation is stopped, do nothing
if (!demoAnimating) return;
// Calculate the maximum x value so the box stays inside
const maxX = demoArea.clientWidth - demoBox.clientWidth;
// If we reached the end, stop the animation
if (demoX >= maxX) {
demoAnimating = false;
return;
}
// Move the box a few pixels to the right
demoX += 3;
demoBox.style.left = demoX + "px";
// Request the next animation frame
requestAnimationFrame(step);
}
// Start button: only start if not already animating
demoStart.addEventListener("click", () => {
if (!demoAnimating) {
demoAnimating = true;
requestAnimationFrame(step);
}
});
// Reset button: stop and move the box back to the start
demoReset.addEventListener("click", () => {
demoAnimating = false;
demoX = 0;
demoBox.style.left = "0px";
});
</script>
transform and opacity for smoother, GPU-accelerated animations.requestAnimationFrame() instead of very fast setInterval() for smoother motion.clearInterval() when the animation is done or no longer needed.display: none to prevent them from taking up space.setInterval().requestAnimationFrame() to slide a green ball smoothly across the screen.