How do I change the background color with JavaScript?

Viewed 721682

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

22 Answers

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";

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

document.body.style.backgroundColor = 'pink';

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;

Alternatively, if you wish to specify the background color value in rgb notation then try

document.getElementById("yourid").style.backgroundColor = `rgb(${a}, ${b}, ${c})`;

where a,b,c are the color values

Example:

document.getElementById("yourid").style.backgroundColor = 'rgb(224,224,224)';
<!DOCTYPE html>
<html>
<body>
<select name="" id="select" onClick="hello();">
    <option>Select</option>
    <option style="background-color: #CD5C5C;">#CD5C5C</option>
    <option style="background-color: #F08080;">#F08080</option>
    <option style="background-color: #FA8072;">#FA8072</option>
    <option style="background-color: #E9967A;">#E9967A</option>
    <option style="background-color: #FFA07A;">#FFA07A</option>
</select>
<script>
function hello(){
let d = document.getElementById("select");
let text = d.options[d.selectedIndex].value;
document.body.style.backgroundColor=text;
}
</script>
</body>
</html>

Add this script element to your body element, changing the color as desired:

<body>
  <p>Hello, World!</p>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#ff0000";  // red
  </script>
</body>

Here are 2 ways to Change Background Color Using Javascript

  1. To change background color with javascript you can apply style.background or style.backgroundColor on the element you want to change background for.

    The below example changes the background color of the body when you click an element using style.background property.

function pink(){ document.body.style.background = "pink"; }
function sky(){ document.body.style.background = "skyblue"; }
<p onclick="pink()" style="padding:10px;background:pink">Pink</p>
<p onclick="sky()" style="padding:10px;background:skyblue">Sky</p>


  1. Another approach could be by adding a CSS class using javascript that gives a background to the element it is attached.

    You can see more ways to add class using javascript but here you can simply use classList.add() property.

        function addClass(yourClass){
            document.body.classList.remove("sky", "pink");
            document.body.classList.add(yourClass);
        }
        .pink {
            background: pink;
        }
    
        .sky {
            background: skyblue;
        }
        <p onclick="addClass('pink')" style="padding:10px;background:pink">Pink</p>
        <p onclick="addClass('sky')" style="padding:10px;background:skyblue">Sky</p>

so you can done very easily by just calling a function like

 function changeBg()
    {
      document.body.style.color.backgroundColor="#ffffff";

    }

It can be achieved using

document.body.style.color.backgroundColor="#000000";

This code makes random color for background every second.

setInterval(changeColor,1000);
function changeColor(){
  let r = Math.random() * 255 ;
  let g = Math.random() * 255 ;
  let b = Math.random() * 255 ;
  
  document.body.style.backgroundColor = `rgb( ${r}, ${g}, ${b} )`;
}

I hope helps someone.❤

 <p id="p1">Hello, Moazzam!</p>
 <p >Hello, Moazzam!</p>
 <p >Hello, Moazzam!</p>
 <script type="text/javascript">
 document.getElementById("p1").style.color= "#ff0000";  // red
 </script>
Related