JavaScript - DOM Animation

Hello, future web developers! Today, we're going to embark on an exciting journey into the world of JavaScript DOM animation. As your friendly neighborhood computer science teacher, I'm thrilled to guide you through this fascinating topic. Trust me, by the end of this lesson, you'll be making web pages come alive with motion!

JavaScript - DOM Animation

Animate DOM Elements with JavaScript

Before we dive into the nitty-gritty of animation, let's quickly recap what the DOM is. DOM stands for Document Object Model, and it's essentially a programming interface for HTML documents. It represents the structure of a document as a tree-like hierarchy, allowing us to manipulate web page content and structure using JavaScript.

Now, when we talk about animating DOM elements, we're referring to changing their properties over time to create the illusion of movement or transformation. It's like creating a flip book animation, but with code!

Let's start with a simple example:

<div id="myBox" style="width: 100px; height: 100px; background-color: red; position: absolute;"></div>

<script>
let box = document.getElementById('myBox');
let position = 0;

function moveBox() {
    position += 1;
    box.style.left = position + 'px';
}

setInterval(moveBox, 10);
</script>

In this example, we're moving a red box across the screen. Let's break it down:

  1. We create a <div> element with some initial styles.
  2. We use document.getElementById('myBox') to get a reference to our box.
  3. We define a moveBox() function that increments the position and updates the left style property of the box.
  4. We use setInterval() to call moveBox() every 10 milliseconds, creating a smooth animation.

Animate DOM elements using setInterval() method

The setInterval() method is one way to create animations in JavaScript. It repeatedly calls a function at specified intervals. Here's a more complex example:

<div id="bouncer" style="width: 50px; height: 50px; background-color: blue; border-radius: 25px; position: absolute;"></div>

<script>
let bouncer = document.getElementById('bouncer');
let x = 0;
let y = 0;
let dx = 2;
let dy = 2;

function animate() {
    x += dx;
    y += dy;

    if (x > window.innerWidth - 50 || x < 0) dx = -dx;
    if (y > window.innerHeight - 50 || y < 0) dy = -dy;

    bouncer.style.left = x + 'px';
    bouncer.style.top = y + 'px';
}

setInterval(animate, 10);
</script>

This script creates a bouncing ball effect:

  1. We set up initial positions (x, y) and velocities (dx, dy).
  2. In the animate() function, we update the position based on the velocity.
  3. We check if the ball hits the edges of the window and reverse its direction if it does.
  4. We update the ball's position on the screen.
  5. setInterval() calls animate() every 10ms, creating smooth motion.

Animate DOM elements using requestAnimationFrame() method

While setInterval() works, modern browsers offer a more efficient method: requestAnimationFrame(). This method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.

Let's rewrite our bouncing ball using requestAnimationFrame():

<div id="bouncer" style="width: 50px; height: 50px; background-color: green; border-radius: 25px; position: absolute;"></div>

<script>
let bouncer = document.getElementById('bouncer');
let x = 0;
let y = 0;
let dx = 2;
let dy = 2;

function animate() {
    x += dx;
    y += dy;

    if (x > window.innerWidth - 50 || x < 0) dx = -dx;
    if (y > window.innerHeight - 50 || y < 0) dy = -dy;

    bouncer.style.left = x + 'px';
    bouncer.style.top = y + 'px';

    requestAnimationFrame(animate);
}

requestAnimationFrame(animate);
</script>

The main difference here is that instead of using setInterval(), we're calling requestAnimationFrame(animate) at the end of our animate() function. This creates a loop where the browser calls animate() just before each repaint.

Animate DOM Elements by changing the CSS Properties

So far, we've been changing CSS properties directly using JavaScript. However, modern web development often leverages CSS transitions and animations for smoother performance. Let's see how we can trigger CSS animations using JavaScript:

<style>
.box {
    width: 100px;
    height: 100px;
    background-color: purple;
    position: absolute;
    transition: all 0.5s ease;
}
</style>

<div id="myBox" class="box"></div>

<script>
let box = document.getElementById('myBox');
let position = 0;

function moveBox() {
    position += 50;
    box.style.transform = `translateX(${position}px)`;

    if (position < 200) {
        requestAnimationFrame(moveBox);
    }
}

box.addEventListener('click', function() {
    position = 0;
    requestAnimationFrame(moveBox);
});
</script>

In this example:

  1. We define a CSS class with a transition property.
  2. Our JavaScript function changes the transform property instead of left.
  3. We use requestAnimationFrame() to create a smooth animation.
  4. The animation starts when the box is clicked.

This method often results in smoother animations because the browser can optimize CSS transitions.

Here's a table summarizing the methods we've discussed:

Method Pros Cons
setInterval() Simple to understand and implement Can be less efficient, may cause jank
requestAnimationFrame() More efficient, syncs with browser's refresh rate Slightly more complex to implement
CSS Transitions Very smooth, can be hardware accelerated Limited control over animation steps

Remember, animation can greatly enhance user experience, but it should be used judiciously. Too much animation can be distracting or even cause motion sickness for some users.

That's it for our journey into JavaScript DOM animation! I hope you've enjoyed this lesson as much as I've enjoyed teaching it. Keep practicing, keep animating, and most importantly, keep having fun with code!

Credits: Image by storyset