Here's how to make nifty slideshows
with image switching.

var timer = null var counter = 1 Start by creating two variables. 'timer' is for referencing the setTimeout method. This is how JavaScript times the execution of different events. The 'counter' variable keeps track of which image you are at.

Below is the function for the timer.

function slideshow() {

Here is the timer that causes the delay between the switching of the images. the number '2000' means 2 seconds. It is measured in thousandths of a second.

timer=setTimeout("slideshow()", 2000);

Now here you incrementing the counter by one.

counter++;

This statement is saying if the counter is greater than or equal to 6 (which is one more than the actual number of pictures) than reset the counter to 2. This actually starts the loop from the second picture. If you want it to start from the first picture, use 1 instead.

if (counter >= 6) counter = 2;

By putting the pictures in an array you can refer to them with the counter. As the counter increments, it changes the source picture.

document.pictures.src = pic[counter].src; }

This function ends the slideshow by clearing out the timer and putting the first picture in and resetting the counter back to 1.

function endtimer() { clearTimeout(timer); document.pictures.src = pic[1].src; counter = 1; }

All of the above goes inbetween the 'HEAD' tags.

Below is the code for precaching the images. They go after the 'BODY' tag.

if (document.images) { pic = new Array(); pic[1] = new Image(108, 108); pic[1].src = "pic1.gif"; pic[2] = new Image(108, 108); pic[2].src = "pic2.gif"; pic[3] = new Image(108, 108); pic[3].src = "pic3.gif"; pic[4] = new Image(108, 108); pic[4].src = "pic4.gif"; pic[5] = new Image(108, 108); pic[5].src = "pic5.gif"; } Be sure to name your slideshow picture like I did below.

<IMG SRC="pic1.gif" WIDTH="171" HEIGHT="171" NAME="pictures"><P>

You activate the slideshow with the link. Instead of linking to another HTML page, you link to your function so that they are activated when you click on the button

<a href="Javascript:void(slideshow())"> <IMG SRC="on.gif" WIDTH="55" HEIGHT="51" BORDER="0" NAME="start"></a> <a href="Javascript:void(endtimer())"> <IMG SRC="off.gif" WIDTH="55" HEIGHT="51" BORDER="0" NAME="stop"></a> </CENTER>

Click here for the code all in one piece.

Example Code

Click here to see how to adapt the code to automatically trigger the slideshow when the page loads.

|menu|