WWW FAQs: How do I display a randomly selected image?


2007-09-18: to randomly insert one of a group of images into a web page, you can use this simple JavaScript code. Just insert this code where you would otherwise place an ordinary <img> element. Note the comments: you must set images to the correct number of images, and you must name your images image1.jpg, image2.jpg, etc. in order to use this script with them.

A different image will appear at the appropriate point in the page every time the page is loaded or reloaded.

If the user has disabled JavaScript, the image backupimage.jpg appears instead.


<script>
<!--
// CHANGE THIS to the number of images that exist.
// YOU MUST NAME YOUR IMAGE FILES image1.jpg, image2.jpg,
// image3.jpg, etc. up to and INCLUDING this number.
images = 7;
number = Math.floor(Math.random(1) * images) + 1;
document.write("<img src=\"image" + number + ".jpg\"/>");
// -->
</script>
<noscript>
<img src="backupimage.jpg"/>
</noscript>

"But what if I want the image to be a link?"

That's easy! Just remember that the code output by document.write becomes part of the page exactly as if it had appeared at the point in the page where the script element is located.

If you had an ordinary <img> element, you would wrap a link around it like this:


<a href="http://www.boutell.com/">
<img src="myimage.png"/>
</a>

So to wrap a link around a randomly chosen image, we simply put both the script and the noscript elements inside our a element, like this:


<!-- Open the link -->
<a href="http://www.boutell.com/">
<script>
... Script code goes here as shown above
</script>
<noscript>
... Alternative image goes here
</noscript>
<!-- Close the link -->
</a>

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!