animation

Animation in JavaScript

Animation in JavaScript

JavaScript can be used to animate elements on a webpage. The setInterval() and requestAnimationFrame() methods are commonly used for animations.

Basic Animation Example

Here’s an example of how to animate a box across the screen using setInterval():

      
        let box = document.getElementById("animateBox");
        let position = 0;
        let interval = setInterval(function() {
          if (position < 300) {
            position += 5;
            box.style.left = position + "px";
          } else {
            clearInterval(interval);
          }
        }, 20);
      
    

Activity

Try It Yourself!

Animate an object on your webpage to move in any direction (up, down, left, right) using JavaScript.

Quiz

Quick Quiz

  1. What is the purpose of setInterval() in JavaScript?
  2. What is the advantage of using requestAnimationFrame()?
  3. What method would you use to stop an animation created by setInterval()?

Answers: It repeatedly calls a function at specified intervals; it is more efficient for animations; clearInterval().