Thursday, February 17, 2011

Random background image in a table cell

Been scouring the internet to look for this function: Making a table cell background to change randomly. There were many I came across but almost 80% were untested or too much work to integrate them into a website. By far the following script is the most simple and basic of them all.

The following is not my script is not written by me (I've forgotten which forum I found it..):

<body>
<script type="text/javascript">
window.addEventListener?window.addEventListener('load',function()
{
ray.rand('thisCell');
},false):
window.attachEvent('onload',function()
{
ray.rand('thisCell');
}); // FF : IE1

var ray=
{
bgArr:['url(bg1.jpg)','url(bg2.jpg)'], // Background you wish to show on the cell
rand:function(el)
{
var num = Math.floor(Math.random()*this.bgArr.length);
this.getID(el).style.background=this.bgArr[num];
},
getID:function(el){return document.getElementById(el);
}
</script>
<table>
<tr>
<td width="900" height="600" id="thisCell">This is the cell</td>
</tr>
</table>
</body>


Happy Coding!

No comments: