JavaScript Animation

HOW TO USE JavaScript ANIMATION

JavaScript is one of the most interesting programming languages Today we will create a box and move it horizontally.

Before we begin, you should already have basic knowledge on HTML 5, CSS and beginners knowledge on JavaScript(DOM).

CREATING OUR HTML CONTAINER

container {
width : 200px;
height : 200px;
background : black;
position : relative;
}
box {
width : 50px;
height : 50px;
background : red;
position : absolute;
}
</style>
</head>
<body>
<div id ="container">
<div id="box"></div>
</div>
</body>

in the code above, we created a container and a box and then we styled it with CSS. (we have a red box inside a black container) NOTE : To create an animation relative to a container, the position must be absolute.

ADDING THE "setInterval()" METHOD

To animate we have to change properties of an element at a small interval of time....Thats where 'setInterval()' method comes in. SetInterval() method allows us to create a timer and calls a function to change properties at the defined time interval. For instance,

var t = SetInterval(move, 10) ;

The above creates a timer that calls move() function every 10 milliseconds. Back to our box

Before adding our setInterval() , We need to first define the move() function that changes the position of our box (This is done inside the script tag or on your external js file).

/ starting position

var pos = 0; 
// our box element
var box = document.getElementById("box");
function move() {
 pos += 1;
  box.style.left = pos+"px";

//px = pixel

From the above code, the move() function increments our box elements left property each time it is called. However, this makes our box move continuously to the right forever. To stop the animation when the box reaches the end of the container, we add a check to the move() function to stop the timer. This check is called.......clearInterval() **look at the code below,

function move() {

  if(pos >= 150) {
    clearInterval(t);
  }
  else {
    pos += 1;
    box.style.left = pos+ "px";
  }

}

Now when the left attribute of the box reaches the value of 150, the box gets to the end of the container and stops moving, this is based on our container and box's width of 200px and 50px respectively. So our final code will be….

window.onload = function() 

{
var pos = 0;
// our box element
var box = document.getElementById('box');
var t = setInterval(move, 10);
function move(){
if(pos >= 150) {
clearInterval(t);
}
else {
pos += 1;
box.style.left = pos+'px';
}

}

If you run this code on any browser, you will see our box moving to the left whenever you reload the page but stops once it gets to the edge of the container.

CONCLUSION

My congratulations are in place, you have successfully created your first animation. you can use the same procedure to create and animate other elements......remember, practice makes perfect.