JS HTML DOMLesson #159

HTML DOM Animation

Learn to create HTML animations using JavaScript.

Learn to create HTML animations using JavaScript.


Share

A Basic Web Page

To demonstrate how to create HTML animations with JavaScript, we will use a simple web page:

Example

Example Code

html
Try it Yourself
# My First
 JavaScript Animation

 My animation will go here

Create an Animation Container

All animations should be relative to a container element.

Example

Example Code

html
Try it Yourself
My
 animation will go here

Style the Elements

The container element should be created with style = "position: relative".

The animation element should be created with style = "position: absolute".

Example

Example Code

css
Try it Yourself
#container {
  width: 400px;
  height:
 400px;
  position: relative;

 background: yellow;

 }
#animate {
  width: 50px;
  height:
 50px;
  position: absolute;

 background: red;
}

Animation Code

JavaScript animations 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.

The basic code is:

Example

Example Code

javascript
Try it Yourself
id = setInterval(frame, 5);

function frame() {
  if (/*
 test for finished */) {
    clearInterval(id);
  } else {

 /* code to change the element style */
  }
}

Create the Full Animation Using JavaScript

Example

Example Code

javascript
Try it Yourself
function myMove() {

  let id = null;

  const elem = document.getElementById("animate");

  let pos = 0;

  clearInterval(id);
  id = setInterval(frame, 5);

 function frame() {
    if (pos ==
 350) {

 clearInterval(id);
    } else {

 pos++;
      elem.style.top = pos + 'px';
      elem.style.left = pos + 'px';

      }
  }
}

Interactive Code Examples

JS Example 1

html
Try it Yourself
JavaScript syntax and algorithm demonstration.
<!DOCTYPE html>
<html>
<body>

<h1>My First 
 JavaScript Animation</h1>


<div id="animation">My animation will go here</div>


</body>
</html>

JS Example 2

html
Try it Yourself
JavaScript syntax and algorithm demonstration.
<div id ="container">
  <div id ="animate">My 
 animation will go here</div>
</div>

JS Example 3

css
Try it Yourself
JavaScript syntax and algorithm demonstration.
#container {
  width: 400px;
  height: 
 400px;
  position: relative;
  
 background: yellow;

 }
#animate {
  width: 50px;
  height: 
 50px;
  position: absolute;
  
 background: red;
}

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
id = setInterval(frame, 5);

function frame() {
  if (/* 
 test for finished */) {
    clearInterval(id);
  } else {

      
 /* code to change the element style */  
  }
}

JS Example 5

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: