Most web pages are a mixture of text and images and, in many cases, the images are a single, static picture. However, with just a little Javascript code it is possible to turn the single image into a whole gallery of pictures which change automatically.
Adding a Static Image to a Web Page
It is, of course, very easy to add an image to a web page by using the img tag:
However, this is a static image. It will not change. The next stage is to add some Javascript in order to change the picture being displayed
Changing an Image by Using Javascript
In order to change the displayed picture the Javascript code must:
- obtain the image element
- change the src of the image
And this can be done with just two lines of code:
This code would change the picture being displayed from the original (image1.png) to a new one (image2.png). Next a timer is required so that all of the changes are done within a continous loop.
Adding a Javascript Loop
A Javascript loop is created by defining a function that calls itself using the setTimeout function, for example:
In the example above the callMe function will repeat once every 2 seconds (or 2000 milliseconds).
Creating the Image Gallery with Javascript
The image gallery consists of a set of images (stored in an array) and a loop that automatically changes the src of an img tag. The array is defined by:
Here 2 images have been used, but more can be added if required. Next a loop counter is required. This will keep track of the image being displayed:
The loop counter is updated by a looping function. The function receives the img tag to be updated and the time for which the image is to be displayed:
The Javascript tales control of the img object:
And then updates the src with a new image:
The loop counter is then updated:
However, the loop counter must not excede the number of available images (as defined by the array):
And finally the function resubmits itself:
All that's required now is the HTML defining the img tag:
And for the loop to be started:
rollover("img1",2000);
< /script>
< /body>
< /html>
If this is now stored as an HTML document and viewed in a browser then the user will see a looping gallery of images that updates itself once every 2 seconds.