Displaying a random image on a web page using JavaScript involves the following steps:
Let's suppose we plan to display one image from a set of 5 images, r1.gif, r2.gif, r3.gif, r4.gif and r5.gif. We create an array called img_rnd and store the image names in it.
var img_rnd = new Array ("r1.gif", "r2.gif",
"r3.gif", "r4.gif", "r5.gif");
Remember, JavaScript arrays are zero indexed (the first element of an array in JavaScript has an index of 0). The Math.random() method returns a value between 0.0 and 1.0. We have to convert this value to an integer between 0 to 4 so that it can be used as an index to retrieve the image name from the img_rnd array. We store the final value in a variable i.
var i = Math.floor(4*Math.random());
The above code can be broken into two parts for easy understanding:
The final step is to display the image through document.write() method.
document.write('<img src="' + img_rnd[i] + '" width="100"
height="100" alt="Random image" />');
We now place all this code between <script>-</script> tags.
<script language="JavaScript">
<!--
var img_rnd = new Array ("r1.gif", "r2.gif",
"r3.gif", "r4.gif", "r5.gif");
var i = Math.floor(4*Math.random());
document.write('<img src="' + img_rnd[i] + '" width="100"
height="100" alt="Random image" />');
//-->
</script>
The Result
Click on the refresh button of the web browser to reload this page. And if you are lucky (80% chance), you'll see another image below.
Page contents: JavaScript code for randomly displaying images on a web page.
Comments, questions, feedback... whatever!