TalentJR

🟨 JavaScript tutorial for beginners · Class 8 · Lesson 16 of 18 · Free

Simple Animations – Make Things Move with JavaScript and CSS

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Animate smoothly with a CSS transition switched on by JavaScript
  • Move an element step by step with setInterval and requestAnimationFrame
  • Start a CSS keyframe animation on click and reset it when it ends

A cartoon is just many still pictures shown very fast. Each picture is a little different, so your eyes see movement. JavaScript animation works the same way. In this lesson, you make a ball roll, a car race and a button bounce.

How do I animate an element with a CSS transition and JavaScript?

The easiest animation needs almost no JavaScript. In CSS, write `transition: …` on an element. Then, whenever a style changes, the browser slides smoothly to the new value.

JavaScript only flips a class with `classList.toggle` (Lesson 5). The browser draws all the in-between frames for you.

Click the button. The box glides to the right and turns orange. Click again to bring it back.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Click Move! to start the transition

💡 Try it: change 0.6s to 2s in the <style> for a slow-motion box.

How does animation work, frame by frame?

Every animation is a loop: change a number a little, draw, repeat. The number is the **position**, and the step size is the **speed**.

To bounce off a wall, we flip the speed: `speed = -speed`. Then the ball moves the other way.

No page here — just watch `pos` and `speed` change in the animation.

🎬 How JavaScript thinks — step 1 of 25JavaScript is about to run line 1
▶let pos = 60;
2let speed = 20;
3const wall = 100;
4
5for (let frame = 1; frame <= 5; frame++) {
6 pos = pos + speed;
7 if (pos >= wall) {
8 speed = -speed; // bounce back!
9 }
10 console.log(`Frame ${frame}: pos = ${pos}`);
11}
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Frame 1: pos = 80
Frame 2: pos = 100
Frame 3: pos = 80
Frame 4: pos = 60
Frame 5: pos = 40

💡 Try it: change speed to 30. Which frame hits the wall now?

How do I move a ball with setInterval in JavaScript?

Now the same loop, but with time between the steps. `setInterval` from Lesson 14 runs every 30 ms. Each time, we add 6 to the position and set `style.left`.

Two important details. The element needs `position: relative` (or absolute), or `left` does nothing. And the value needs **px**: `"120px"`, not `120`.

When the ball reaches 240px, we stop the interval.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Rolling…
🏏 Ball stopped at 240px

💡 Press ▶ Run again to replay. Try it: change 6 to 2 for a slow ball.

What is requestAnimationFrame in JavaScript?

`requestAnimationFrame(fn)` asks the browser: "run fn just before you draw the next picture". Screens draw about 60 pictures a second, so the movement is very smooth.

It runs only one time, so the function asks again at the end: `requestAnimationFrame(drive)`. When the car reaches the finish, we simply stop asking.

Notice: pass `drive`, the function name, without brackets — the same rule as setTimeout.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
🏁 Finished in 50 frames

💡 Try it: change 5 to 10. The car is twice as fast and needs half the frames.

How do I start a CSS keyframe animation with JavaScript?

CSS `@keyframes` describe a whole dance: start here, go up, come down. Adding a class plays it.

But adding a class that is already there does nothing, so the dance would play only once. The fix: listen for `animationend` and remove the class when the dance is over.

Click the diya many times. It bounces every time.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Click the diya!

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

let x = 0;
for (let i = 0; i < 4; i++) {
  x = x + 25;
}
console.log(x + "px");

Question 2. What does this print?

let pos = 90;
let speed = 20;
pos = pos + speed;
if (pos > 100) {
  speed = -speed;
}
console.log(pos, speed);

Question 3. What does this print?

const step = 10;
const frames = 3;
console.log(`translateX(${step * frames}px)`);

🧩 Your challenge

Launch a **Diwali rocket**! The rocket starts at the bottom (`bottom: 0px`). Every 20 ms, move it up by 10px using `style.bottom`. When it reaches 150px, stop the interval, change it to 🎆 and print where it stopped. Expected output: ``` 🎆 Rocket burst at 150px ```

Expected output in the console:
🎆 Rocket burst at 150px
🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const box = document.querySelector("#box");
box.style.left = 100;
console.log("left is:", box.style.left);

No error, but the box does not move: left is still empty, because 100 has no "px".

✅ Right

const box = document.querySelector("#box");
box.style.left = 100 + "px";
console.log("left is:", box.style.left);

CSS sizes need a unit. A bare number like 100 is ignored, so left stays empty. Write "100px".

❌ Wrong

const box = document.querySelector("#box");
box.style.transform = translateX(100px);

SyntaxError: Invalid or unexpected token

✅ Right

const box = document.querySelector("#box");
box.style.transform = "translateX(100px)";
console.log(box.style.transform);

A CSS value is text for JavaScript, so it needs quotes. Without quotes, JavaScript tries to read 100px as code.

❌ Wrong

const ball = document.querySelector(".ball");
ball.style.left = "50px";

TypeError: Cannot read properties of null (reading 'style')

✅ Right

const ball = document.querySelector("#ball");
ball.style.left = "50px";
console.log("Moved to", ball.style.left);

The ball has an id, so the selector needs #. .ball looks for a class, finds nothing and gives null.

📌 Remember

  • Animation = change a value a little, draw, repeat — many times a second.
  • CSS transition + classList.toggle is the easiest smooth animation.
  • setInterval or requestAnimationFrame can move things step by step; always stop them.
  • style.left needs position: relative/absolute and a unit: x + "px".
  • Re-play a keyframe animation by removing its class on animationend.

Finished the quiz and the challenge?

Questions students ask

Should I use CSS or JavaScript for animation?

Use CSS transitions or keyframes for simple effects like hover, slide and bounce — they are short and smooth. Use JavaScript when the movement depends on logic, like a game ball that bounces off walls.

What is the difference between setInterval and requestAnimationFrame?

setInterval runs at the gap you choose. requestAnimationFrame runs just before each screen refresh, usually 60 times a second, so it is smoother. It also pauses when the tab is hidden, which saves battery.

Why is my element not moving when I change style.left?

Two common reasons. The element needs position: relative or absolute in CSS. And the value needs a unit, like "50px", not just 50.

Can I make games with JavaScript animation?

Yes. Most browser games use a requestAnimationFrame loop: move everything a little, check for hits, draw, and repeat. What you learnt here is the start of that.