Answer: Use the JavaScript style property You can easily change the background color of a webpage i.e. the <body> element or any other element dynamically by using its style property in JavaScript.
The background-color CSS property sets the background color of an element.
You can set a background color for an HTML document by adding style="background-color:" to the <body> element.
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.
AJAX is getting data from the server using Javascript and XML in an asynchronous fashion. Unless you want to download the colour code from the server, that's not what you're really aiming for!
But otherwise you can set the CSS background with Javascript. If you're using a framework like jQuery, it'll be something like this:
$('body').css('background', '#ccc');
Otherwise, this should work:
document.body.style.background = "#ccc";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With