Discuss Can't change background color in the JavaScript Development forum on Dev Shed. Can't change background color JavaScript Development forum discussing JavaScript and DHTML, AJAX, and issues such as coding cross-browser JavaScript.
Posts: 9
Time spent in forums: 3 h 10 m 4 sec
Reputation Power: 0
Other - 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.
PHP Code:
<script type = "text/javascript">
function bgChanger()
{
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;
}
}
</script>
Here's the form.
PHP Code:
<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>
</select>
</form>
Posts: 19,835
Time spent in forums: 6 Months 1 Day 22 h 11 m
Reputation Power: 4192
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".
Quote:
Originally Posted by web_loone08
I like to use the DOM method; when I change the style of elements, because I think the above method
may be depreciated, in the future. I change the background color; like so:
document.getElementsByTagName("body")[0].style.backgroundColor = "#0000ff";