January 13th, 2013, 06:47 PM
Can't change background color
I'm trying to make a function which will change the background color of a page from a dropdown menu.
I'm not sure why it doesn't work; any help or tips would be great.
This is the function. I don't know where or what's wrong with it.
Here's the form.
defaultcolor = window.document.bgColor;
backcolorvalue = window.document.bgchanger.bg.selectedIndex;
backcolor = window.document.bgchanger.bg[backcolorvalue].value;
if (backcolorvalue == 0)
window.document.bgcolor = '#0040FF';
else if (backcolorvalue == 1)
window.document.bgcolor = '#CC00FF';
else if (backcolorvalue == 2)
window.document.bgcolor = '#CCFFCC';
else if (backcolorvalue == 3)
window.document.bgcolor = '#FFFF33';
else if (backcolorvalue == 4)
window.document.bgcolor = defaultcolor;
<form name = "bgchanger">
<select name = "bg" onChange = "bgChanger()">
<option value = "blue">Blue</option>
<option value = "red">Red</option>
<option value = "green">Green</option>
<option value = "yellow">Yellow</option>
<option value = "default">Default</option>
January 13th, 2013, 07:17 PM
January 13th, 2013, 08:28 PM
January 14th, 2013, 03:29 PM
Jacques1: Thank you very much. I probably wouldn't have been able to figure this out on my own.
Kravvitz: I don't know any CSS right now so I might just be sticking with what I'm using D:
Thanks for letting me know though.
January 14th, 2013, 04:29 PM
All right, consider this your first lesson. The "background-color" property takes the same values as the old bgColor attribute (plus many more).
For example, you can set the background to blue with either of these:
document.body.style.backgroundColor = '#0000ff';
document.body.style.backgroundColor = 'blue';
Comments on this post
January 14th, 2013, 10:49 PM
So basically I should just replace bgColor with backgroundColor?
Originally Posted by Kravvitz
January 14th, 2013, 10:54 PM
January 15th, 2013, 12:20 AM
Yes, replace "window.document.bgColor" with "document.body.style.backgroundColor". The "window.", in your original code, would only be necessary if you had a local variable named "document".
Yes, "document.body" is the old way, but I don't see it going away any time soon and it's so much shorter than using getElementsByTagName(). Both are part of the DOM2 standards.
Originally Posted by web_loone08
Comments on this post