w1coding.comAll tutorials

JavaScript Animation

JavaScript lessons
  1. Environment Setup
  2. Introduction
  3. Enviroment
  4. Basics
  5. Variables
  6. Operators
  7. Condition
  8. Functions
  9. Arrays
  10. Bjects
  11. DOM
  12. Objects
  13. Colors
  14. DOM
  15. Events
  16. Validation
  17. JSON
  18. Error
  19. Callbacks
  20. Promises
  21. Fetch
  22. Local
  23. Modules
  24. Animation
  25. Classes
  26. Iframes
  27. Responsive

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().