Categories
Web development

JavaScript HTML DOM/Animations

Learn how to create HTML animations using JavaScript.

JavaScript HTML DOM Animations
  1. Create an Animation Container – all animations should be relative to a container element.
<div id ="content">
  <div id ="animate">The animation will go here.</div>
</div>

2. Style the Elements:

The container element should be created with style =“position: relative”

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

<!Doctype html>
<html>
<style>
#content {
  width: 400px;
  height: 400px;
  position: relative;
  background-color: #e9c46a;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: #264653;
}
</style>
<body>

<div id="content">
<div id="animate"></div>
</div>

</body>
</html>

Output:


3. 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.

function myAnimation() {
  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"; 
    }
  }
}

Example:

<!DOCTYPE html>
<html>
<style>
#content {
  width: 400px;
  height: 400px;
  position: relative;
  background-color: #e9c46a;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: #264653;
}
</style>
<body>

<p><button onclick="myAnimation()">Start!</button></p> 

<div id ="content">
  <div id ="animate"></div>
</div>

<script>
function myAnimation() {
  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"; 
    }
  }
}
</script>

</body>
</html>

Output:


Enjoy coding!

Read also:

JavaScript Introduction

JavaScript HTML DOM