Last Updated on November 29, 2016 by admin

This is documented in many other places on the Internet, but it can’t hurt to have too many tutorials.

You can jazz up your web site with a bit of JavaScript to randomly insert images on your page. I’m doing this on my masthead, as one example.

The first requirement is to build a list of images:

myPix = new Array("images/bridge.jpg", "images/butterfly1.jpg", "images/cats.jpg", "images/ducks.jpg", "images/field1.jpg", "images/field2.jpg", "images/flowers2.jpg", "images/flowers3.jpg", "images/flowers4.jpg"

Then write the code to select one at random:

imgCt = myPix.length;
function choosePic() {
  if(document.images) {
    randomNum = Math.floor((Math.random() * imgCt));
    document.myPic.src = myPix[randomNum];

Finally, you need to set up the HTML to hold the image:

<img id='frontphoto' name='myPic' src='images/bg.gif' />

The name=’myPic’ relates to the JS “document.myPic.src” declaration. The id=’frontphoto’ definition in the <img> tag is the CSS magic that sizes the image. And the ‘images/bg.gif’ is a placeholder image that gets overwritten by the selected image.

That’s it – you can poke around the web site and watch it work.