Display Random Image Using JavaScript
This example uses JavaScript to display an image selected at random from the list you provide. Each time the page loads, a new selection will be made from the list.
There is no guarantee that it won't be the same image that was displayed the previous time. Of course, as you increase the number of items in the list of images you specify, you reduce the likelihood of repeats.
Instructions
Specify your images in an array. Since the array is held in a global variable it's a good idea to give it a long name to avoid any conflicts with other code that may be used in your page.
var random_images_array = ["turtle.gif", "cave-art.gif", "sunset.gif",
"mandala1.gif", "cranes.gif", "design1.gif",
"mandala2.gif", "swans.gif", "deco.gif",
"crystal.gif", "mex-sun.gif", "om.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 the call to the getRandomImage function:
<script type="text/javascript">getRandomImage(random_images_array)</script>
You can either specify a default path inside the getRandomImage function itself (code comments indicate where) or pass the path (i.e., the location of your images) when you call the function:
getRandomImage(random_images_array, '/images/')
The image can be placed inside a link if you like. The link would surround the script segment as follows:
<a href="/"><script type="text/javascript">getRandomImage(random_images_array)</script></a>
In order for the linked image not to be displayed with a border you could 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.
This code is free for all uses. Donations are always appreciated!
Display Random Image Using PHP
See the code that uses PHP to display an image selected at random.