[javascript] How do I change the background color with JavaScript?

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

This question is related to javascript css

The answer is


You can change background of a page by simply using:

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

Read more @ Changing the Background Color


This is simple coding for changing background using javascript

<body onLoad="document.bgColor='red'">

I would suggest the following code:

<div id="example" onClick="colorize()">Click on this text to change the
background color</div>
<script type='text/javascript'>
function colorize() {
var element = document.getElementById("example");
element.style.backgroundColor='#800';
element.style.color='white';
element.style.textAlign='center';
}
</script>

This code makes random color for background every second.

_x000D_
_x000D_
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} )`;
}
_x000D_
_x000D_
_x000D_

I hope helps someone.?


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

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

Css approach:

If you want to see continuous colour, use this code:

body{
    background-color:black;
    animation: image 10s infinite alternate;
    animation:image 10s infinite alternate;
    animation:image 10s infinite alternate;
}

@keyframes image{
    0%{
background-color:blue;
}
25%/{
    background-color:red;
}
50%{
    background-color:green;
}
75%{

    background-color:pink;
}
100%{
    background-color:yellow;
    }
  }  

If you want to see it faster or slower, change 10 second to 5 second etc.


Or...you can just do background(0);, in function draw(); (0 is the color black)


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

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

if you wish to use a button or some other event, just use this in JS:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});

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.


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;

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


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.


Css approach:

If you want to see continuous colour, use this code:

body{
    background-color:black;
    animation: image 10s infinite alternate;
    animation:image 10s infinite alternate;
    animation:image 10s infinite alternate;
}

@keyframes image{
    0%{
background-color:blue;
}
25%/{
    background-color:red;
}
50%{
    background-color:green;
}
75%{

    background-color:pink;
}
100%{
    background-color:yellow;
    }
  }  

If you want to see it faster or slower, change 10 second to 5 second etc.


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

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


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

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

This will change the background color according to the choice of user selected from the drop-down menu:

_x000D_
_x000D_
function changeBG() {_x000D_
  var selectedBGColor = document.getElementById("bgchoice").value;_x000D_
  document.body.style.backgroundColor = selectedBGColor;_x000D_
}
_x000D_
<select id="bgchoice" onchange="changeBG()">_x000D_
    <option></option>_x000D_
    <option value="red">Red</option>_x000D_
    <option value="ivory">Ivory</option>_x000D_
    <option value="pink">Pink</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


But you would want to configure the body color before the <body> element exists. That way it has the right color from the get go.

<script>
    var myColor = "#AAAAAA";
    document.write('\
        <style>\
            body{\
                background-color: '+myColor+';\
            }\
        </style>\
    ');
</script>

This you can put in the <head> of the document or in your js file.

Here is a nice color to play with.

var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

You can change background of a page by simply using:

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

Read more @ Changing the Background Color


You can do it in following ways STEP 1

   var imageUrl= "URL OF THE IMAGE HERE";
   var BackgroundColor="RED"; // what ever color you want

For changing background of BODY

document.body.style.backgroundImage=imageUrl  //changing bg image
document.body.style.backgroundColor=BackgroundColor //changing bg color

To change an element with ID

document.getElementById("ElementId").style.backgroundImage=imageUrl
document.getElementById("ElementId").style.backgroundColor=BackgroundColor 

for elements with same class

   var elements = document.getElementsByClassName("ClassName")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=imageUrl;
        }

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;

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


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 would suggest the following code:

<div id="example" onClick="colorize()">Click on this text to change the
background color</div>
<script type='text/javascript'>
function colorize() {
var element = document.getElementById("example");
element.style.backgroundColor='#800';
element.style.color='white';
element.style.textAlign='center';
}
</script>

You can do it in following ways STEP 1

   var imageUrl= "URL OF THE IMAGE HERE";
   var BackgroundColor="RED"; // what ever color you want

For changing background of BODY

document.body.style.backgroundImage=imageUrl  //changing bg image
document.body.style.backgroundColor=BackgroundColor //changing bg color

To change an element with ID

document.getElementById("ElementId").style.backgroundImage=imageUrl
document.getElementById("ElementId").style.backgroundColor=BackgroundColor 

for elements with same class

   var elements = document.getElementsByClassName("ClassName")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=imageUrl;
        }

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 wouldn't really class this as "AJAX". Anyway, something like following should do the trick:

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

This will change the background color according to the choice of user selected from the drop-down menu:

_x000D_
_x000D_
function changeBG() {_x000D_
  var selectedBGColor = document.getElementById("bgchoice").value;_x000D_
  document.body.style.backgroundColor = selectedBGColor;_x000D_
}
_x000D_
<select id="bgchoice" onchange="changeBG()">_x000D_
    <option></option>_x000D_
    <option value="red">Red</option>_x000D_
    <option value="ivory">Ivory</option>_x000D_
    <option value="pink">Pink</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


But you would want to configure the body color before the <body> element exists. That way it has the right color from the get go.

<script>
    var myColor = "#AAAAAA";
    document.write('\
        <style>\
            body{\
                background-color: '+myColor+';\
            }\
        </style>\
    ');
</script>

This you can put in the <head> of the document or in your js file.

Here is a nice color to play with.

var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

<!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>

This code makes random color for background every second.

_x000D_
_x000D_
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} )`;
}
_x000D_
_x000D_
_x000D_

I hope helps someone.?


<!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>

Or...you can just do background(0);, in function draw(); (0 is the color black)


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

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)';

You can change background of a page by simply using:

document.body.style.background = #000000; //I used black as color code

However the below script will change the background of the page after every 3 seconds using setTimeout() function:

$(function() {
            var colors = ["#0099cc","#c0c0c0","#587b2e","#990000","#000000","#1C8200","#987baa","#981890","#AA8971","#1987FC","#99081E"];

            setInterval(function() { 
                var bodybgarrayno = Math.floor(Math.random() * colors.length);
                var selectedcolor = colors[bodybgarrayno];
                $("body").css("background",selectedcolor);
            }, 3000);
        })

READ MORE

DEMO


This is simple coding for changing background using javascript

<body onLoad="document.bgColor='red'">

if you wish to use a button or some other event, just use this in JS:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});

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.


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

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


You can change background of a page by simply using:

document.body.style.background = #000000; //I used black as color code

However the below script will change the background of the page after every 3 seconds using setTimeout() function:

$(function() {
            var colors = ["#0099cc","#c0c0c0","#587b2e","#990000","#000000","#1C8200","#987baa","#981890","#AA8971","#1987FC","#99081E"];

            setInterval(function() { 
                var bodybgarrayno = Math.floor(Math.random() * colors.length);
                var selectedcolor = colors[bodybgarrayno];
                $("body").css("background",selectedcolor);
            }, 3000);
        })

READ MORE

DEMO


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;