Random Image Display Using JavaScript
Sponsored Links
The steps involved in randomly displaying an image from a set are very similar to those used for displaying random text strings.
- Initializing an array
- Storing the image file names in that array
- Finding the length of this array
- Using the Math.random() to generate a random number
- Using the randomly generated number as index for retrieving an image file name from the array.
- Displaying the image.
var img_name = new Array("purple.gif", "red.gif",
"blue.gif", "yellow.gif", "green.gif", "pink.gif");
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.r_img.src = img_name[rnd_no];
<img src="purple.gif" width="100" height="50"
name="r_img" alt="Random image" />
In th code above, we have JavaScript array containing 6 images. The array length found from length is, thus, 6 - img_name[0] would be "purple.gif", img_name[1] would be "red.gif" and so on. We then use the Math.round() to get a random number, multiply it with the array length and round it up using Math.floor().

Click to display another random image.
Note: Array are zero-indexed, so the last element in the array will the length of the array minus 1. However, since we are employing floor() to get an integer, we can use the value from ARRAY_NAME.length directly.
You can also use the id attribute of the image tag instead of name; as:
var img_name = new Array("purple.gif", "red.gif",
"blue.gif", "yellow.gif", "green.gif", "pink.gif");
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("randomimage").src = img_name[rnd_no];
<img src="purple.gif" width="100" height="50"
id="randomimage" alt="Random image" />

Click to display another random image.
When can you display random images on a web page?
A potential use of the random image displaying code is when you want to show a single banner from a set - though I would prefer using server-side scripts like PHP or Perl for this. I have also employed the code to randomly rotate images at a designated place on the web page.
![]()
- No assignments here.
Page contents:
Comments, questions, feedback... whatever!
Recent Articles
Recent Blog Posts
Popular Articles
- Hotmail Sign In page
- Create a Hotmail account - Instructions
- Create Gmail address
- Download and install Outlook Express
- Get your free Gmail address
- Outlook Express new version
- Create my own email address
- Browers for Windows list
- Get email address
- Color combinations for web sites and pages
- Create Yahoo ID
