Ken Ward's Java Script Tutorial ...

A new image every time you visit the page - nearly!

Random Images

Try reloading this page and see what happens to the image below. The more images you have in your ARRAY the more likely a different image will load. I have used 4 images, so the likelihood of the same image loading again in quite high!

You can experiment without reloading by pressing the button below the image. The new image will appear very quickly, so if the picture doesn't seem to change, the new image is the same as the old one. Click again!

Firstly, we make a list of images, and then preload them:

/* ####################### begins list of images to be used

####################### */

currentIndx=0;

MyImages=new Array();

MyImages[0]='vulcano.gif';

MyImages[1]='eye.gif';

MyImages[2]='ear.gif';

MyImages[3]='hand.gif';

 

/* ####################### now we preload the images ####################### */

imagesPreloaded = new Array(4)

for (var i = 0; i < MyImages.length ; i++)

{

imagesPreloaded[i] = new Image(120,120)

imagesPreloaded[i].src=MyImages[i]

}

Having completed this, we can then choose a random image and load it:

/* ####################### this function loads a random image ####################### */

function newImage() {

// Makes a random, whole number between 0 and 3

currentIndx=Math.round(Math.random()*3)

document.theImage.src=imagesPreloaded[currentIndx].src

}

The image is changed quite easily, by simply making it equal to one of the images in the array imagesPreloaded.

The code in the BODY is:

<table>

<tr>

<!-- the NAME of the image is used to load the new images-->

<td>

<img src="vulcano.gif" name="theImage" id="theImage" alt="Slide Show" height="120" width="120" />

</td>

</tr>

<tr>

<td>

<form>

<p>

<!-- the onClick calls our function newImage()-->

<input type="button" value="Random Image" onclick="newImage()" />

</p>

</form>

</td>

</tr>

</table>

To make this work, you need to call the function when the page has loaded:

<body onload="newImage()">

For an example of this code using a select, click here.

Next: Slide Show Using Frames