« Yahoo messenger problems | Main | I hate IE »

Dirt simple JavaScript to pick a random image

I wanted something to pick a random image for my blog but didn't want to spend more than 5 minutes on it.. so this is what I came up with..

Yes, I know, I could get fancy, use perl, size the images on the fly.. etc.. etc.. but I just don't feel this is worth all that effort :)

It's a very stupid little JavaScript that takes lots of assumptions and took me literally 2 minutes to write, but heck why not share it.

The script itself:

<script LANGUAGE=JavaScript>
<!-- JavaScript begin

  function pickNum() {

    var rval = "";

    var n = 9999; 
    var i = 0;

    while(i == 0) {
       i = Math.round(Math.random()*n);
    }

    if(i < 10) 
       rval = "000" + i;
    else if (i < 100) 
       rval = "00" + i; 
    else if (i < 1000) 
       rval = "0" +i;
    else 
       rval = i;

    return rval;
  }

  var img = "<img border=\"0\" " +
   "src=\"/photographs/random/" + pickNum() + ".jpg\">";

// end -->
</SCRIPT>

To use it to display an image in the page.. just use this somewhere in HTML:

<script LANGUAGE=JavaScript> document.write(img); </script>