Random image display using JavaScript - displaying images randomly on a web page

Sponsored Links

Random image display using JavaScript

Displaying images random involves the following steps:

  • Listing the images you plan to display
  • Storing the names of these images in an array
  • Using the Math.random() method to obtain a random value
  • Displaying the image using document.write() method

Listing the images and storing them in an array

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 now store then in an array img_rnd.

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 and 1. 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.

Generating a random number

var i = Math.round(4*Math.random());

Displaying the image

The final step is to display the image through document.write() method.

document.write('<IMG SRC="' + img_rnd[i] + '" WIDTH="100"
HEIGHT="100">');

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.round(4*Math.random());

document.write('<IMG SRC="' + img_rnd[i] + '" 
WIDTH="100" HEIGHT="100">');

//-->
</SCRIPT>


The Result
Click on the refresh button and if you are lucky (80% chance), you'll see another image below.


Page contents: Random image display using JavaScript - displaying images randomly on a web page

AddThis Social Bookmark Button

HTML & JavaScript Tips