JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Animations


What Are DOM Animations?

DOM Animations refer to the process of moving, transforming, or changing elements on a webpage dynamically using JavaScript. While CSS provides basic animation capabilities, DOM Animations allow programmatic control, making it possible to animate properties like position, size, color, opacity, and more.

DOM Animations make web pages interactive and visually appealing, improving user experience.

Why DOM Animations Are Important

JavaScript animations are important because they allow you to:

  • Create dynamic and interactive UI elements.

  • Provide visual feedback for user actions.

  • Enhance user engagement through motion.

  • Control animations based on events or logic.

  • Combine movement, style changes, and timing flexibly.

Modern web applications often rely on DOM Animations for sliders, carousels, modals, progress bars, and visual effects.

Ways to Animate DOM Elements

Using setInterval or setTimeout

You can update an element’s properties repeatedly using a timer:

let box = document.querySelector(".box");
let position = 0;

let interval = setInterval(() => {
    if (position >= 300) {
        clearInterval(interval); // Stop animation
    } else {
        position++;
        box.style.left = position + "px";
    }
}, 10);

Explanation:

  • The box moves 1px every 10 milliseconds until it reaches 300px.

  • setInterval repeats a function at a fixed time interval.

  • clearInterval stops the animation once the goal is reached.

Using requestAnimationFrame

requestAnimationFrame is more efficient than setInterval because it synchronizes animation with browser refresh rate, providing smoother animations.

let box = document.querySelector(".box");
let position = 0;

function animate() {
    if (position < 300) {
        position++;
        box.style.left = position + "px";
        requestAnimationFrame(animate);
    }
}

animate();

Benefits:

  • Smoother and more performant.

  • Automatically pauses animations when the tab is inactive.

  • Preferred method for modern web animations.

Animating Multiple Properties

You can animate multiple CSS properties at once:

let box = document.querySelector(".box");
let size = 50;

function growBox() {
    if (size < 200) {
        size++;
        box.style.width = size + "px";
        box.style.height = size + "px";
        box.style.opacity = size / 200; // Gradually increase opacity
        requestAnimationFrame(growBox);
    }
}

growBox();

Explanation: The box grows in size and fades in at the same time.

Event-Driven Animations

Animations can be triggered by user interactions like clicks, hover, or scroll events.

Hover Animation Example

let box = document.querySelector(".box");

box.addEventListener("mouseover", () => {
    box.style.transform = "scale(1.2)";
    box.style.transition = "transform 0.3s ease";
});

box.addEventListener("mouseout", () => {
    box.style.transform = "scale(1)";
});

Explanation: The box zooms in on hover and returns to original size smoothly.

Click Animation Example

let button = document.getElementById("animateBtn");
let box = document.querySelector(".box");
let left = 0;

button.addEventListener("click", () => {
    function move() {
        if (left < 300) {
            left += 5;
            box.style.left = left + "px";
            requestAnimationFrame(move);
        }
    }
    move();
});

Clicking the button moves the box horizontally across the screen.

Combining Animations with CSS Transitions

CSS transitions make animations smoother without writing a complex loop:

let box = document.querySelector(".box");
box.style.transition = "all 0.5s ease";

document.getElementById("changeBtn").addEventListener("click", () => {
    box.style.width = "200px";
    box.style.height = "200px";
    box.style.backgroundColor = "blue";
});

Explanation:

  • The transition property animates width, height, and background color changes smoothly.

  • JavaScript only changes the styles; the browser handles the animation.

Using Keyframes with JavaScript

While CSS keyframes are usually defined in CSS, you can trigger them dynamically using JavaScript:

let box = document.querySelector(".box");
box.style.animation = "slide 2s forwards";
@keyframes slide {
    0% { left: 0; }
    100% { left: 300px; }
}

Explanation: Keyframes define the animation, while JavaScript applies it dynamically.

Practical Example: Combined Animation

<div class="box" style="width:50px; height:50px; background:red; position:relative;"></div>
<button id="startBtn">Start Animation</button>
let box = document.querySelector(".box");
document.getElementById("startBtn").addEventListener("click", () => {
    let pos = 0;
    function animate() {
        if (pos < 300) {
            pos++;
            box.style.left = pos + "px";
            box.style.top = (pos / 2) + "px";
            box.style.backgroundColor = `rgb(${pos % 255}, 100, 150)`;
            requestAnimationFrame(animate);
        }
    }
    animate();
});

Explanation: This animation moves the box diagonally and changes its color dynamically.

Best Practices for DOM Animations

  • Prefer requestAnimationFrame over setInterval for smoother animations.

  • Minimize layout thrashing by updating styles efficiently.

  • Use CSS transitions or keyframes when possible for better performance.

  • Combine event-driven triggers for interactivity.

  • Avoid animating expensive properties like width and height if possible; prefer transform and opacity for smoother performance.

Summary of the Tutorial

JavaScript DOM Animations allow you to move, transform, and style elements dynamically on a webpage. Key concepts include:

  • Using setInterval or setTimeout for basic animations.

  • Using requestAnimationFrame for smoother, high-performance animations.

  • Animating multiple CSS properties simultaneously.

  • Triggering animations via events such as click, hover, or scroll.

  • Combining CSS transitions, keyframes, and JavaScript for advanced effects.

Mastering DOM Animations is crucial for building interactive, engaging, and responsive web interfaces.


Practice Questions

  1. Animate a <div> element to move 300px to the right using requestAnimationFrame.

  2. Create a <div> that grows in width and height from 50px to 200px gradually.

  3. Animate a <div> to change its background color smoothly from red to blue.

  4. Create a hover effect on a <div> that enlarges the box and changes its color on mouseover, and reverts on mouseout.

  5. Move a <div> diagonally across the screen from top-left to bottom-right.

  6. Animate multiple boxes to move in sequence when a button is clicked.

  7. Animate a box’s opacity from 0 to 1 over 2 seconds.

  8. Rotate a box 360 degrees smoothly when a button is clicked.

  9. Animate a box to move back and forth horizontally (ping-pong effect).

  10. Combine position, size, and color changes in a single animation triggered by a button click.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top