Sunday, February 4, 2007

Random Table Background Image

This was a quick hack for a friend to get a random background image set for a table. You should be able to add this just about anywhere in the <body> tag. This would also work just for a table cell.

<script language="javascript">
<!--
onload = function() {
/* If you change the directory, make sure you update it here. */
var imageDirectory = "http://www.yourwebsite.com/images/";
/* If you want to add more images on your own, put the the file name in the middle
of the list here. Make sure there are quotes around it and a comma at the end. */
var imageArray = new Array("image3.gif",
"image6.gif",
"image1.gif",
"image4.gif",
"image2.gif",
"image5.gif");
var imageArrayLength = imageArray.length; // Leave these next few lines alone
var pseudoRandomNumber = ( Math.round( Math.random() * (imageArrayLength - 1) ) );
document.getElementById("tableImage").style.backgroundImage="url('" +
"imageDirectory + imageArray[pseudoRandomNumber] + "')";
}
//-->
</script>
<noscript>
<style type="text/css">
#tableImage {
background-image:url('http://www.yourwebsite.com/images/image3.gif');
}
</style>
</noscript>

<table id="tableImage" height="431" width="465">
<tr><td> </td></tr>
</table>

UPDATE: This is OLD. You should look for a better solution.

1 comment:

Anonymous said...

Well this is fantastic. I got it working in just a few minutes.

Ever think of a 2.0 version?

A nice feature would be to also change the image every xx seconds after loading :)

Thank you for your effort and sharing this online.

Kind regards,

Chris