Animation means making elements move or change over time.
In web development, animation can:
With JavaScript, we can control animation step-by-step.
Ways to Create Animation in JavaScript
There are 3 main ways:
1️⃣ Using setInterval()
2️⃣ Using setTimeout()
3️⃣ Using requestAnimationFrame() (Best & Modern Way)
Basic Example: Moving a Box
Let’s animate a square box moving from left to right.
Step 1: Create HTML
<div id="box"></div> <button onclick="startAnimation()">Start Animation</button>
Step 2: Add CSS (For Style)
<style>
#box {
width: 50px;
height: 50px;
background-color: blue;
position: relative;
}
</style>
Important:
position: relative; allows the box to move using left.
Method 1: Using setInterval()
setInterval() runs code repeatedly every X milliseconds.
Example
function startAnimation() {
const box = document.getElementById("box");
let position = 0;
const interval = setInterval(function () {
position += 2;
box.style.left = position + "px";
if (position >= 300) {
clearInterval(interval);
}
}, 10);
}
How This Works:
Method 2: Using setTimeout()
setTimeout() runs code once after a delay.
We can call it repeatedly to create animation.
function startAnimation() {
const box = document.getElementById("box");
let position = 0;
function move() {
if (position < 300) {
position += 2;
box.style.left = position + "px";
setTimeout(move, 10);
}
}
move();
}
This works similarly to setInterval().
Method 3: requestAnimationFrame()
This is the modern and best way.
Why?
function startAnimation() {
const box = document.getElementById("box");
let position = 0;
function animate() {
if (position < 300) {
position += 2;
box.style.left = position + "px";
requestAnimationFrame(animate);
}
}
animate();
}
Why requestAnimationFrame Is Better
✔ Smoother
✔ Matches screen refresh rate
✔ Saves CPU power
✔ Automatically pauses in background tabs
Changing Other Properties
You can animate:
1️⃣ Opacity (Fade In)
let opacity = 0; box.style.opacity = opacity;
Increase gradually to 1.
2️⃣ Size
box.style.width = "100px"; box.style.height = "100px";
3️⃣ Rotation
box.style.transform = "rotate(45deg)";
Important Concept: Frames
Animation works by:
This creates the illusion of movement.
Most screens refresh at 60 frames per second (FPS).
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Animation Example</title>
<style>
#box {
width: 50px;
height: 50px;
background-color: blue;
position: relative;
opacity: 1;
}
</style>
</head>
<body>
<h2>JavaScript Animation Example</h2>
<div id="box"></div>
<br>
<button onclick="startAnimation()">Start Animation</button>
<script>
function startAnimation() {
const box = document.getElementById("box");
let position = 0;
let opacity = 1;
function animate() {
if (position < 300) {
position += 2;
opacity -= 0.003;
box.style.left = position + "px";
box.style.opacity = opacity;
box.style.transform = "rotate(" + position + "deg)";
requestAnimationFrame(animate);
}
}
animate();
}
</script>
</body>
</html>