Simple animations using JavaScript

This tutorial explains how to use the HTML5 canvas element and JavaScript to animate a div in a webpage. Below is a preview of what the animation will look like. Scroll down to see the code.

animdiv

Refer to the comments in the code below to find out what is happening on each line.

<html>
<head>
<title>My animation</title>
<style type="text/css">
 
#animatedBox{
 /* simple box */
 position:absolute; /* The element is positioned relative to its first positioned (not static) ancestor element */
 top:30px; /* This is the position of the box from the top */
 width:200px; /* This is the width of the box */
 line-height:20px; /* This is the height of the box */
 background:#58FA82; /* This is the background colour of the box */
 border:1px solid #0B610B; /* This is the border thickness and border colour of the box */
 padding:10px; /* This is the padding amount around the text in the box */
 
 /* Hint: Get colour codes from http://html-color-codes.info/ */
}
 
</style>
<script type="text/javascript">
 
var box ; // create the variable we will use as the object to animate
 
function doMove() {
 box.style.left = parseInt(box.style.left)+1+'px'; // parseInt parses a string and returns an integer, moves 1 pixel from left
 setTimeout(doMove,20); // call doMove in 20 milliseconds
}
 
function init() {
 box = document.getElementById('animatedBox'); // get the "box" object
 box.style.left = '0px'; // set its initial position to 0px
 doMove(); // call the doMove function to start animating!
}
 
 
window.onload = init; // load the init function when the page loads
 
</script>
</head>
 
<body>
 
<div id="animatedBox">
 <b>My animation</b>
</div>
 
</body>
</html>

Next tutorial: Animating (moving) an image using JavaScript