Some times we need to randomize the images at same place with minimum script and occupy less memory and to decrease the size of a web page. There are lots of demos and examples available on net.I customize the code for one of my projects. It is tested and working fine on all today’s major browsers (IE7, Firefox 3, Safari 3, Google Chrome).

Lets dig into the code…

The Math.floor() method returns the floor of the specified number or expression. The floor of a number is the closest integer that is less than or equal to the number. The Math.random() method returns a random number between 0 and 1. I used a for loop to randomize the max number of images. So that I don’t need to specify each image name in my function. I am passing variable a in img[] array. And variable i will randomize the for loop.

Here is the complete working randomImage() function:

function randomImage(){
  var img = new Array();
  var img_path = "/path_of/images/";
  var img_name = "image_";
  var img_ext = ".gif";
  var img_id = document.getElementById("image_id");
  for(var a= 0; a < 8; a++){
    img[a] = img_path + img_name + a + img_ext;
  }
  var i = Math.floor (Math.random() * a);
  img_id.src = img[i];
}

Now call the randomImage function in a page where you want to be.

<script type="text/javascript">window.onload=randomImage;</script>

You just need to specify the image tag with height and width of the image if all images are of same width and height.

<img id="image_id" width="214" height="259" />

And your browser will render the following result:

<img height="214" width="259" id="image_id" src="/path_to/images/image_1.gif"/>

Save your document. And refresh it to get the above result.
If you want to make auto refresh the page use the meta tag:

<meta http-equiv="refresh" CONTENT="5;URL=html_document.html">

Where 5 is the delay of seconds.