View Full Version : automatic text colour changer

08-20-2002, 04:15 PM
Hello..i was trying to make a script that changed the colours of my text every so often:-

function changecolor()

colours=new Array()



<BODY onLoad='javascript:changecolor()'>Welcome

However, the problem is, when u load the page, nothing happens!!! no script errors or nothing, and the text does not change color. I heard sometimes this kind of animation or whatever its called doesn't work in MSIE later versions, so i tried Opera, but it doesnt work there either. I can't figure it out, i have set it to run on body onLoad, but it doesnt do a thing! Anybody made a script like this and know what i have done wrong or missed out?

08-20-2002, 05:47 PM
Well, first of all, the javascript: in the onLoad is unecessary, and you have quite a few errors in your javascript. First of all, you don't properly declare colours. Should be
var colours = new Array() But even then it is far more efficient to populate the Array at time of creation. Also, the loops serve no purpose. And, you shouldn't be using document.fgColor anymore. Better use document.body.style.color instead. Here's the code I came up with that works
function changecolor() {
var colours = new Array('green','blue','yellow','red','gold','silver\');
var rand = Math.floor(Math.random() * colours.length);
document.body.style.color = colours[rand];
setTimeout("changecolor();",30000); // Every 30 seconds.
<body onLoad="changecolor()">

08-20-2002, 06:35 PM
Thanks u for ur help.......the reason for the first loop was to designate how many times i wanted it to change colours...i have 5 colours therefore each colour would get repeated 4 times this way (5x4=20)...the other loop was to give some time between each colour change otherwise it would be too fast...but the settimeout way is a much more efficient way as i can see.
Anyway thanks so much 4 the help!!:cool:

08-20-2002, 06:37 PM
one more thing, has document.fgColor been killed off?

08-20-2002, 06:43 PM
I'm not positive, but I'm pretty sure that (fgColor) is deprecated by the W3C

Also, I know you are now familiar with the setTimout function, but it's important that you understand that that trying to use a loop for a delay is not just less efficient, it's pretty much impossible. Loops are run at the maximum speed the computer can handle. Most machines out there now will run through an 800 count loop fast...REAL fast, especially one that has no operations within it. For most cases, you would need over 500,000 iterations to generate a delay of close to 1-2 seconds. (Well, except for NS, which doesn't have the loop optimization that IE does...)