• 20 hours
  • Easy

Free online content available in this course.

course.header.alt.is_certifying

Got it!

Last updated on 8/5/19

Bring pages to life

Log in or subscribe for free to enjoy all this course has to offer!

This chapter will get you started with JavaScript for animations! We'll see how to kick off animations which should run repeatedly or which should stop at a certain point.

Repeat at an action at regular intervals

A great place to start is to learn how to repeatedly modify an element's content. Go ahead and add the following HTML to your course code.

<!doctype html>
<html>

    <head>
        <meta charset="utf-8">
        <title>Animate a page</title>
    </head>

    <body>
        <h1 id="title">This page will self-destruct in...<span id="counter">10</span> second(s)...</h1>

        <script src="../js/course.js"></script>
    </body>

</html>

Add the following code to its corresponding JavaScript file.

var counterElement = document.getElementById("counter");

// Count down the counter until 0
function decreaseCounter() {
// Convert counter text to a number
    var counter = Number(counterElement.textContent);
    counterElement.textContent = counter - 1;
}

// Call the decreaseCounter function every second (1000 milliseconds)
setInterval(decreaseCounter, 1000);

Open the page in your browser, and see that it works! Or...kind-of works. The animation never stops. We'll fix this a little later.

Kick off a repeated action

How did our example work? The JavaScript program defined a function called decreaseCounter that accesses and then decreases one by one the value of the HTML element. Calling Number converts the counter string into a number, which endows it with the subtraction functionality.

The call to setInterval triggers the counting action. This function lets you call a function at regular intervals. Its parameters are the 1) function to call and 2) time between each call in milliseconds.

Stop a repeated action

Let's try to stop the counter once the countdown is complete. We'll also modify the text of the page. Here's the JavaScript code for our example, updated to produce our desired result.

var counterElement = document.getElementById("counter");

// Decrease the counter by 1 until 0
function decreaseCounter() {
    // Convert the counter text to a number
    var counter = Number(counterElement.textContent);
    if (counter > 1) {
        counterElement.textContent = counter - 1;
    } else {
    // Cancel the repeated execution
        clearInterval(intervalId);
        // Modify the page title
        var title = document.getElementById("title");
        title.textContent = "BOOM!!";
    }
}

// Call the decreaseCounter function every second (1000 milliseconds)
var intervalId = setInterval(decreaseCounter, 1000);

In the decreaseCounter function, we only decrease the counter if the current value is higher than 1. If not, we call the function clearInterval and then modify the title of the page.

The clearInterval function lets you cut off repeated code execution. It takes the ID of the action as a parameter, sent by the  setInterval  function and stocked in the intervalID variable (in our example).

Trigger an action after a delay

Imagine that you want to modify the page text after its "explosion" in the previous example. You'd modify our example as follows:

var counterElement = document.getElementById("counter");

// Decrease the counter to 0
function decreaseCounter() {
    // Convert the counter text to a number
    var counter = Number(counterElement.textContent);
    if (counter > 1) {
        counterElement.textContent = counter - 1;
    } else {
        // Cancel the repeated action
       clearInterval(intervalId);
        // Modify the page title
        var title = document.getElementById("title");
        title.textContent = "BOOM!!";
        // Modify the title after 2 seconds
        setTimeout(function () {
            title.textContent = "Everything's broken ";
        }, 2000);
    }
}

// Call the decreaseCounter function every second (1000 milliseconds)
var intervalId = setInterval(decreaseCounter, 1000);

Once the countdown has finished, we call setTimeout to set a new page title after a 2 second delay.

Animate page elements

The previous solutions were convenient for making our pages more dynamic but weren't enough for adding real-time animations. Let's look at a better-performing solution.

Take, for example, the movement of a div type element from left to right on the page. Add this HTML snippet in the <body> of your sample page.

<head>
    <style type="text/css">
        #frame {
            border: 1px solid red;
        }

        #block {
            width: 20px;
            height: 40px;
            background: red;
            position: relative;
        }
    </style>
</head>
<body>
    <div id="frame">
        <div id="block"></div>
    </div>
</body>

Here's the JavaScript code that lets you move the red block.

var frame = document.getElementById("frame");
var block = document.getElementById("block");
// convert the block diagram into a number ("XXpx")
var blockDiameter = parseFloat(getComputedStyle(block).width);
var movement = 7; // Movement value in pixels

// Move the block to the left
function moveBlock() {
    // convert the left position of the block to a number ("XXpx")
    var xBlock = parseFloat(getComputedStyle(block).left);
    // Moving the block
    block.style.left = (xBlock + movement) + "px";
    // Have the browser call moveBlock as soon as possible
    requestAnimationFrame(moveBlock);
}
requestAnimationFrame(moveBlock); // Start of the animation

If you open the page in your browser, it works, but again, the block never stops moving!

Start an animation

Our code example defines a function called moveBlock which moves the block horizontally. It grabs the current position of the block's left border than adds the value contained in the movement  variable. Next, it calls the requestAnimationFrame method to keep the animation going.

Position values are written in pixels. These are the strings you saw that resemble "XXpx," which requires the use of parseFloat to convert numeric values before making calculations.

The requestAnimationFrame function lets you ask the browser to execute a function as soon as possible, which updates the animation.

Stop an animation

Let's now see how to stop the block before it reaches the frame that contains it. We'll have to verify that the left border position is less than the width of the frame, bearing in mind the thickness of the block itself.

Here's the modified JavaScript:

var frame = document.getElementById("frame");
var block = document.getElementById("block");
var movement = 7;
var blockWidth = parseFloat(getComputedStyle(block).width);
var animationId = null; // animation ID

// Move the block from the left, all the way to the end of the frame
function moveBlock() {
    var xBlock = parseFloat(getComputedStyle(block).left);
    var xMax = parseFloat(getComputedStyle(frame).width);
    if (xBlock + blockWidth <= xMax) { // if the block isn't already to the end of the frame
        // Block movement
        block.style.left = (xBlock + movement) + "px";
        animationId = requestAnimationFrame(moveBlock);
    } else {
        // Cancel the animation
        cancelAnimationFrame(requestId);
    }
}

animationId = requestAnimationFrame(moveBlock); // Start the animation

The new moveBlock function checks that the block has arrived at the end of the frame before moving. If that's the case, the animation stops via a call to cancelAnimationFrame.

The cancelAnimationFrame function stops the animation and takes the identification of the animation, stored here in the variable animationId and sent with each call torequestAnimationFrame.

Alternative: CSS animations

We just learned about the different possibilities that JavaScript offers for animating web pages. Just bear in mind there's another alternative: CSS!

CSS animation example

Let's check out how to get a similar effect as the previous example by using CSS instead of JavaScript.

Modify your CSS above as follows.

#block {
    width: 20px;
    height: 40px;
    background: red;
    position: relative;
    margin-left: -20px;
    animation-name: moveBlock;
    animation-duration: 6s;
    animation-fill-mode: forwards;
}

@keyframes moveBlock {
    from {
        /* Initial position: to the left of the frame) */
        left: 20px;
    }
    to {
        /* Final position: within the right side of the frame) */
        left: 100%;
    }
}

This code uses a CSS animation called moveBlock, which moves the block from the left to the right side of its containing frame.

Now, decision time. How should you choose between setInterval,requestAnimationFrame, or CSS to make your animation? It depends how complex your animation is. In theory, CSS animations are more efficient performance-wise, but you can't do everything with them.

Here's how you might want to approach your decision:

  • Use setInterval if the animation isn't in real-time and should just happen at regular interval.

  • Use CSS if the animation happens in real-time. If you can handle it via CSS, use CSS.

  • Use requestAnimationFrame for any other case.

Summary

  • The setInterval function kicks off a repeated action and is called at regular intervals. TheclearInterval function stops a repeated action that was launched with  setInterval .

  • The setTimeout function executes an action once after a certain delay.

  • The requestAnimationFrame function asks the browser to execute a function that updates the animation as soon as possible. This works well for real-time animations. ThecancelAnimationFrame function stops an in-progress animation that was launched withrequestAnimationFrame.

  • You can also create web animations via CSS.

  • The clearInterval function lets you stop a repeated action. You'll need to pass the identified action as a parameter, which is stocked in intervalId in our example.

Example of certificate of achievement
Example of certificate of achievement