Display a Random Image Using JavaScript

On this page we present a simple JavaScript that displays an image selected at random from a list you provide. Each time the page loads, a new selection will be made from the list.

Setup is easy: include an array containing your images, and place a script segment where you want the random image to display in your layout. Details on these steps are provided below. A download file includes an example.

Instructions

Place your images in an array. The array is held in a global variable, so a long name like random_images_array will help avoid conflicts with any other JavaScript in your page:

var random_images_array = ["img1.gif", "img2.gif", ...];

The following function is called to display the random image. The function, as well as the array of images, can be placed in the head of your document in a script segment or in an external JavaScript file.

function getRandomImage(imgAr, path) {
    path = path || 'images/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();
}

Place a script segment where you wish the random image to appear in your layout. Include the name of the array holding your images in a call to the getRandomImage function:

<script type="text/javascript">getRandomImage(random_images_array);</script>

You can either specify a default path to your images inside the getRandomImage function itself (code comments indicate where), or pass the path in the function call:

<script type="text/javascript">getRandomImage(random_images_array, '/images/');</script>

The random image can be placed inside a link if you like. The link would surround the script segment as shown here:

<a href="/"><script type="text/javascript">getRandomImage(random_images_array);</script></a>

To ensure that the linked image will not be displayed with a border, include the following in the style sheet:

a img { border:none; }

You can display more than one random image in your page if you like, either from the same list or a different one.

Download Code - It's Free!

A download file includes the script and example. See also a PHP script that displays an image selected at random from a directory listing.