skip to content
randomscripts logo Scripts the webs worst backgrounds la gavage oregon milkweed project contact

Random Background Color Changer

This script automatically changes the background color of the page at a set interval. It does this by generating three different random numbers, which are then used to pick color values from an array. The color values are two-digit segments of the six-digit hexidecimal code that is used to represent the color. This example uses the 216 "web-safe" colors, those which are composed of combinations of the letters/numbers 00, 33, 66, 99, CC and FF.

Hexidecimal color codes are composed of the pound sign (#) followed by three sets of two digits which represent the value of red, green and blue in a color. An example is bright Red, which is represented by the hex code #FF0000. Blue is #0000FF, Green is #00FF00, White is #FFFFFF and Black is #000000. The lower the number, the darker the color, and conversely, the higher the number, the lighter the color.

#FF00FF       #FF9933       #00CC00       #3399FF
#FF6600       #336633       #CC0000       #FF0099
#6633CC       #33CCFF       #0000CC       #99FF33

In order to use this script, you will need to insert the following code into the header section of your HTML document (preferably right before the </HEAD> tag):


var secs = 1;

var i = new Array(6);
i[0] = "00";
i[1] = "33";
i[2] = "66";
i[3] = "99";
i[4] = "cc";
i[5] = "ff";

function swapBG(){
var j = Math.floor(Math.random()*6);
var k = Math.floor(Math.random()*6);
var l = Math.floor(Math.random()*6);

var nC1 = i[j];
var nC2 = i[k];
var nC3 = i[l];

var newColor = nC1 + nC2 + nC3

document.bgColor = newColor;

setTimeout("swapBG()", secs * 1000);



Step 2 is to modify the <BODY> tag to read:

<BODY onload="swapBG()">

Finally, you will need to set the value of var secs = 1 to the number of seconds you want to elapse between color changes. This can be set to a decimal number less than one for times shorter than one second.

That's it! If you want to restrict the colors to only dark colors or only light colors, you can remove some of the array elements corresponding to the unwanted values. Remove 00, 33, and 66 to eliminate dark colors. Remove 99, CC and FF to eliminate light colors. If you do remove some values, remember to renumber the remaining array elements:

var i = new Array(3);
i[0] = "00";
i[1] = "33";
i[2] = "66";

Also reset the values in the random variable statements to coincide with the number of elements in the array:

var j = Math.floor(Math.random()*3);
var k = Math.floor(Math.random()*3);
var l = Math.floor(Math.random()*3);

This will reduce the number of colors, but will help keep the background light or dark depending on your preference.

Copyright © 2002 randomscripts, All Rights Reserved.     Disclaimer