This page demonstrates how to use JavaScript to generate a random background colour whenever the page is loaded or refreshed. You obviously have to be careful when choosing the background colours to ensure that whichever is chosen the text can still be read.

To produce this effect, in the HEAD section of the page put...

<script language="javascript">
<!-- Hide the script from old browsers
function clrChange(){
//Define and populate the array
var hexNum = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
//Generate 6 random numbers, and add that array index to rdmHexClr
for (cnt=1;cnt<7;cnt++){
rdmNum=Math.floor(Math.random()*hexNum.length);
rdmHexClr = rdmHexClr + hexNum[rdmNum];
}
rdmHexClr = "#" + rdmHexClr;
document.bgColor=rdmHexClr;
}
-->
</script>

Change the BODY tag to read...

<body onload=clrChange()>

To use only the "web-safe" colours, the code in the head section should be...

<script language="javascript">
<!-- Hide the script from old browsers
function clrChange(){
//Define and populate the array
var hexNum = new Array("00","33","66","99","CC","FF");
//Generate 3 random numbers, and add that array index to rdmHexClr
for (cnt=1;cnt<4;cnt++){
rdmNum=Math.floor(Math.random()*hexNum.length);
rdmHexClr = rdmHexClr + hexNum[rdmNum];
}
rdmHexClr = "#" + rdmHexClr;
document.bgColor=rdmHexClr;
}
-->
</script>

This page created 22nd October 2004, last modified 24th October 2004


GoStats stats counter