Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Color transition using setTimeout 1

Status
Not open for further replies.

Zhris

Programmer
Aug 5, 2008
254
0
0
GB
I have written a simple program which is designed to change the background colour of a DIV every second (from rgb 1,1,1 through to rgb 255,255,255) creating a transition effect. I'm unsure what I am doing wrong and I can't get it working. Any ideas?

Code:
window.onload=Ftrans(0);
function Ftrans(i){
	d=document.getElementById('main');
	d.style.backgroundColor='rgb(' + i + ',' + i + ',' + i + ')';
	if(i<=255){
		setTimeout("Ftrans(i+1)",1*1000);
	}
}

Thanks,

Chris
 
There are 3 problems that I can see.

The way you're setting the onload handler means the function runs immediately, instead of onload. To avoid this issue, change this:

Code:
window.onload=Ftrans(0);

to this:

Code:
window.onload = function() { Ftrans(0); };

The second problem is that your "i" loop will actually run to 256 instead of 255. Change your test from this:

Code:
if(i<=255){

to this:

Code:
if (i < 255) {

The last issue is with the setTimeout call itself. You are never incrementing "i", rather passing a string "i+1" as the parameter. To avoid this, remove the addition from inside the quotes by changing this:

Code:
setTimeout("Ftrans(i+1)",1*1000);

to this:

Code:
setTimeout('Ftrans(' + (i+1) + ')', 1000);

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Thank you for such a quick response Billy,

I made the suggested changes, which has got the program working/looping, but there is no color transition. Could it be my CSS use of rgb?

Thanks,

Chris
 
It will work fine given my changes. You're probably not waiting the required 4.25 minutes for the effect to finish.

You could reduce your time between steps from 1 second by changing the 1000 to 10. Then you'd only have to wait a short time to see the effect.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Ah my mistake, I had mistakenly deleted a character. Thank you, its working absolutely perfectly!

Chris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top