JavaScript HTML DOM Animation

Learn to create HTML animations using JavaScript.

Basic page

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

Example

<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript Animation</h1>
<div id="animation">My animation is here.</div>
</body>
</html>

Create animation container

All animations should be associated with the container element.

Example

<div id ="container">
    <div id ="animate">My animation is here.</div>
</div>

Add styles to elements

should be created through style = "position: relative" to create container elements.

should be created through style = "position: absolute"Create animation elements."

Example

#container {
    width: 400px;
    height: 400px;
    position: relative;
    background: yellow;
elem.style.left = pos + 'px';
#animate {
    width: 50px;
    height: 50px;
    position: absolute;
    background: red;
elem.style.left = pos + 'px'; 

}

Animation Code

JavaScript animation is programmed by gradually changing the element style.

This change is achieved by calling a counter. When the counter interval is very small, the animation looks smooth.

The basic code is:

Example

var id = setInterval(frame, 5);
function frame() {
    if (/* Test if completed */) {
        clearInterval(id);
    else {
         /* Code to change element style */
    elem.style.left = pos + 'px';
elem.style.left = pos + 'px'; 

Create Animation with JavaScript

Example

function myMove() {
    var elem = document.getElementById("animate"); 
    var pos = 0;
    var id = setInterval(frame, 5);
     function frame() {
        if (pos == 350) {
             clearInterval(id);
        else {
             } 
             pos++; 
             elem.style.top = pos + 'px'; 
        elem.style.left = pos + 'px';
     elem.style.left = pos + 'px';
elem.style.left = pos + 'px';

}