Home : Internet : JavaScript : Random Image

How to Display a Random Image

Use the code below to display a random image on your web page. You specify a list of images and the code chooses one of them at random. See below for more instructions.

<script type="text/javascript">
 var imlocation = "images/";
 var currentdate = 0;
 var image_number = 0;
 function ImageArray (n) {
   this.length = n;
   for (var i =1; i <= n; i++) {
     this[i] = ' '
 image = new ImageArray(3)
 image[0] = 'image1.gif'
 image[1] = 'image2.gif'
 image[2] = 'image3.gif'
 var rand = 60/image.length
 function randomimage() {
 	currentdate = new Date()
 	image_number = currentdate.getSeconds()
 	image_number = Math.floor(image_number/rand)
 document.write("<img src='" + imlocation + randomimage()+ "'>");

To Substitute Your Own Images

Change the imlocation variable to show the correct location of your images.

Swap the file names in the ImageArray() for your own.

To use a different number of images, add each new image on a line of its own, following the same format. You also need to change the number in the ImageArray() to reflect the total number of images (remember to count the "zero"). For example:

image = new ImageArray(5)
image[0] = 'image1.gif'
image[1] = 'image2.gif'
image[2] = 'image3.gif'
image[3] = 'image4.gif'
image[4] = 'image5.gif'

Note: This script uses the current time to create an effect which is effectively random. You may need to wait quite a few seconds between page reloads to see the different images appear.


To make each image a hyperlink, see this variation.

Subscribe to us on YouTube