views:

6875

answers:

7

Anyone know a simple method to swap the background color of a webpage using javascript?

+1  A: 

Why do you need AJAX? Isn't background color easily changed client side?

Esteban Araya
+7  A: 

Modify the JavaScript property document.body.style.background.

For example:

function changeBackground(color) {
   document.body.style.background = color;
}

<BODY onload="changeBackground(red)">

This is pure JavaScript, nothing to do with AJAX :)

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.

Phill Sacre
Cool, thanks much.
Anders
+1  A: 

I wouldn't really class this as "AJAX". Anyway, something like following should do the trick:

document.body.style.backgroundColor = 'pink';
Duncan Smart
+1  A: 

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.

Simon Lehmann
+1  A: 

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";
Oli
A: 

I would prefer to see the use of a css class here. It avoids having hard to read colors / hex codes in javascript.

document.body.className = className;

redsquare
+2  A: 

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 kindof give the page a certain state.

Martin Kool