i2tutorials

Javascript DOM- Animations

Javascript DOM- Animations

 

Animation Code:

 

JavaScript animations are done by programming gradual changes in an element style(css).

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

 

The basic code is:

 

Example:

 

var id = setInterval(frame, 5);
function frame() {
  if (/* test for finished */) {
      clearInterval(id);
  } else {
     /* code to change the element style */
  }
}

 

Example:

 

<!DOCTYPE html>
<html>
<style>
#container {
 width: 400px;
 height: 400px;
 position: relative;
 background: black;
}
#animate {
 width: 100px;
 height: 100px;
 position: absolute;
 background-color: green;
}
</style>
<body>

<p>
<button onclick="myMove()">Click Me</button>
</p>

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

<script>
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';
   }
  }
}
</script>

</body>
</html>

 

OUTPUT:

 

Javascript DOM- Animations

 

 

Exit mobile version