DOM Animations

HTML animation is used to provide some animation.

To understand how to create HTML animations by using JavaScript, we will create a simple web page:

<!DOCTYPE html>
<html>
<body>

<h1>My JavaScript Animation World</h1>

<div id="myAnimation">My animation will work here</div>

</body>
</html>

Create an Animation Container

We will provide all animations to a container element.

<div id ="myContainer">
  <div id ="myAnimation">My animation will work here</div>
</div>

Style the Elements

The container element will have style = “position: relative“.

The animation element will have style = “position: absolute“.

Input:-
<!Doctype html>
<html>
   <style>
      #myContainer {
      width: 200px;
      height: 200px;
      position: relative;
      background: grey;
      }
      #myAnimation {
      width: 40px;
      height: 40px;
      position: absolute;
      background: yellow;
      }
   </style>
   <body>
      <h2>My JavaScript Animation World</h2>
      <div id="myContainer">
         <div id="myAnimation"></div>
      </div>
   </body>
</html>

Output :-


Animation Code

HTML animations by JavaScript are done by programming gradual changes in an element’s style.

The changes are called by a timer. When the timer interval is small, the animation looks continuous.

Below is example to understand this:

var id = setInterval(frame, 6);

function frame() {
  if (/* test after finished */) {
    clearInterval(id);
  } else {
    /* code to change the element style or to provide some animation */ 
  }
}

Create the Full Animation Using JavaScript

<!DOCTYPE html>
<html>
   <style>
      #myContainer {
      width: 200px;
      height: 200px;
      position: relative;
      background: grey;
      }
      #myAnimation {
      width: 40px;
      height: 40px;
      position: absolute;
      background: yellow;
      }
   </style>
   <body>
      <p><button onclick="runAnimation()">Click Here</button></p>
      <div id="myContainer">
         <div id="myAnimation"></div>
      </div>
      <script>
         var id = null;
         function runAnimation() {
           var elem = document.getElementById("myAnimation");   
           var pos = 0;
           clearInterval(id);
           id = setInterval(frame, 6);
           function frame() {
             if (pos == 150) {
               clearInterval(id);
             } else {
               pos++; 
               elem.style.top = pos + "px"; 
               elem.style.left = pos + "px"; 
             }
           }
         }
      </script>
   </body>
</html>

Output (Before Click):-

Output (Before Click):-