Lecture 9 – JavaScript Animation

In this chapter, we will briefly study how we can use JavaScript to add aminations to our HTML elements. Some of the animated affects you can create using JavaScript include the following.

  • Fade affect
  • Fireworks
  • Page-in or Page-out
  • Roll-in or Roll-out
  • Objective movements

Developers frequently use the following functions to create complex animations in the JavaScript.

  • setTimeout( function, duration) − This function calls function after duration milliseconds from now.
  • setInterval (function, duration) − This function calls function after every duration milliseconds.
  • clearTimeout (setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions.

It is also possible to manipulate DOM using these functions. For example, changing the position of an object on the screen is a very common DOM manipulation technique in JavaScript. In this method, JavaScript assigns a number of attributes to an HTML element such as top and left to change the object’s position. Take a look at the following example.

<html>   
   <head>
      <title>JavaScript Animation</title>      
      
         
      
   </head>
   
   <body>   
      <form>
         <img id = "theImage" src="balloon.jpg" width="300" height="300">
         <p>Click button below to move the image to right</p>
         <input type = "button" value = "Click Me" onclick = "moveRight();" />
      </form>      
   </body>
</html>

Here is how the code will transform in the browser.

Now, if you click on the button, the mouse will start moving to the right as indicated by the following figure.

Here is how the code will transform in the browser.

Now, if you click on the button, the mouse will start moving to the right.

We also have used certain functions related to DOM manipulation. We briefly explain them one by one in the lines below.

  • getElementById(): it is the function to get a DOM object. We also used this function to assign value to the global variable chPosition.
  • init(): this particular function initializes the chPosition function in addition to setting its left attribute and position. This function is called when the window loads.
  •  moveRight(): we have used this function to move the image to the right by 10 pixels.

In the next lecture, we will study JavaScript Dialog Boxes.