JavaScript Animation | Java Script Tutorial - Learn with VOKS
Back Next

JavaScript Animation


Animation means making elements move or change over time.

In web development, animation can:

  • Move objects
  • Change colors
  • Fade elements in/out
  • Resize elements
  • Rotate items

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:

  • Every 10 milliseconds, position increases by 2.
  • The box moves right.
  • When it reaches 300px, animation stops.


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?

  • Smoother animation
  • Optimized by browser
  • Better performance
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:

  1. Updating a value
  2. Redrawing the screen
  3. Repeating many times per second

This creates the illusion of movement.

Most screens refresh at 60 frames per second (FPS).

Example Code:
<!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>
Java Script
Introduction Application of JavaScript Defining JavaScript Client-Side JavaScript JavaScript Syntax JavaScript Varaibles JavaScript Operators JavaScript Statements JavaScript Arrays Sorting JavaScript Array JavaScript Functions JavaScript Objects JavaScript For and For-In Loops JavaScript Cookies JavaScript Form Validation JavaScript Error and Exception Handling JavaScript Animation JavaScript Switch Case and While Loops
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL