How do I change the background color with JavaScript?
Modify the JavaScript property document.body.style.background
.
For example:
function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('red') });
Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.
You don't need AJAX for this, just some plain java script setting the background-color property of the body element, like this:
document.body.style.backgroundColor = "#AA0000";
If you want to do it as if it was initiated by the server, you would have to poll the server and then change the color accordingly.
I agree with the previous poster that changing the color by className
is a prettier approach. My argument however is that a className
can be regarded as a definition of "why you want the background to be this or that color."
For instance, making it red is not just because you want it red, but because you'd want to inform users of an error. As such, setting the className AnErrorHasOccured
on the body would be my preferred implementation.
In css
body.AnErrorHasOccured
{
background: #f00;
}
In JavaScript:
document.body.className = "AnErrorHasOccured";
This leaves you the options of styling more elements according to this className
. And as such, by setting a className
you kind of give the page a certain state.