Animation through Javascript :)


Did u know u could animate ur pages with Javascript...well that's what I'm going to talk about.

Somebody recently posted a question about animation through Javascript and I thought I'll tell u all about it.

Well it's pretty simple once u get a hang of it.

Let's first understand what we have to do. First of all we have to preload all the images we want displayed.

Lets suppose we have an image called plane.gif which we want to preload. Well what we do is first create an image object and then specify it's source as the plane.gif image file.

myImage1 = new Image( )
myImage1.src = "plane.gif "
Note: This code should be in the head tag of the page so that the image is loaded first.

What we should do is add lines of code such as the previous ones to preload the images.

After that in the page onload event we fire off a function (any function) lets say it's called loadimage(). What this function does is load the images one after the other after a small time interval using the timeout() function.

Important: We should also have a default image on the page whose source we will change to display the other images. In our example we shall call it oldimage.

Well I've put the entire source down below so u can check it out.


Here's is the source.
Add the following lines of code inside the <head> tag of the page

-----------following lines of code inside the head tag of the page-----------------

<script langauge="Javascript">
<!-- Hiding code from previous browsers


myImage1 = new Image( )
myImage1.src = "plane.gif "

myImage2 = new Image( )
myImage2.src = "servo.jpg"

myImage3 = new Image( )
myImage3.src = "ship.gif"

myImage4 = new Image( )
myImage4.src = "lpggas.jpg"

myImage5 = new Image( )
myImage5.src = "trees.jpg"

function loadimage( )
{
setTimeout('document.oldimage.src=myImage1.src',6000);
setTimeout('document.oldimage.src=myImage2.src',9000);
setTimeout('document.oldimage.src=myImage3.src',12000);
setTimeout('document.oldimage.src=myImage4.src',15000);
setTimeout('document.oldimage.src=myImage5.src',18000);
}
NOTE: Here oldimage refers to the name of the image which is already present on the html page on which u are writing all this code.
// -->
</script>

-----------------------end of script for head tag--------------------------------
The first few lines of code cause the image to preload before displaying and then the loadimage() uses the Timeout function to diplay the images one after the other.

In the onload event for the page add the following script

<BODY onload="loadimage();return true;">

This will call the function loadimage() which we have defined in the head tag causing the images to display one after the other

I hope u find this interesting. If u have any questions or suggestions u can mail me at sanjay@dbsindia.com.



HOME



This page is maintained by Sanjay Shetty.
Send mail to sanjay@dbsindia.com.

U R visitor no .