SteadmanTech logo image

Display Random Images

Here is a really easy way to have random images for a page. Here are the four steps.

Step 1. Make your images.

When you make your images, they must all be of the same type, like .gif or .jpg

The image file names must all be the same except for an embedded sequential number. Examples:


It doesn't matter how many images you will be using so long as the naming is consistent and the numbers are sequential.

When your images are ready, upload them into a directory on your server.

Step 2. Determine the image tag.

Determine what your image tag would be if you were putting the image directly onto your page. You'll use this tag in the JavaScript function in the next step.

Here is an example image tag:

<img src="logo2.jpg">

If all of your images will have the same height and width, you might also include those in the image tag:

<img src="logo2.jpg" height="150" width="200">

Step 3. Create the JavaScript function.

Put this JavaScript into the HEAD area of your web page, like:


<script type="text/javascript" language="JavaScript">
<!-- Copyright 2002 Bontrager Connection, LLC
// Type the number of images you are rotating.

NumberOfImagesToRotate = 3;

// Specify the first and last part of the image tag. 

FirstPart = '<img src="logo';
LastPart = '.jpg" height="150" width="200">';

function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);


On the line with NumberOfImagesToRotate, replace the number 3 with the number of images you are rotating.

Now, use the last example in the previous step and separate the image tag into two parts. The first part will be the tag up to the sequential number. The last part will be everything following the sequential number. The number itself will not be represented in either the first or last part.

Between the apostrophes following "FirstPart =" and "LastPart =", put the first and last part of your image tag.

That's all you need to do with the JavaScript function. When called, the function will determine a random number from 1 to the NumberOfImagesToRotate. It will then construct the image tag by placing the random number between the FirstPart and LastPart. Last, it will print the constructed image tag with the built-in document.write() function.

Step 4. Insert the random image.

Where you want the random image to appear on your web page, put:

<script type="text/javascript" language="JavaScript"><!--

That's all there is to it.

With only three images, there is a 1 in 3 chance that the same image will display when you reload the page. The more images you have for the randomizer to choose from, the less often the same image will display more than once in a row.