Anyone know a simple method to swap the background color of a webpage using JavaScript?
Kevin Ji
10.4k4 gold badges39 silver badges58 bronze badges
asked Oct 13, 2008 at 14:23
0
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.
Mister Jojo
19k6 gold badges20 silver badges40 bronze badges
answered Oct 13, 2008 at 14:27
0
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.
answered Oct 13, 2008 at 14:27
Simon LehmannSimon Lehmann
10.6k4 gold badges41 silver badges53 bronze badges
2
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.
answered Oct 13, 2008 at 15:03
Martin KoolMartin Kool
4,1884 gold badges25 silver badges36 bronze badges
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";
answered Oct 13, 2008 at 14:30
OliOli
233k63 gold badges218 silver badges295 bronze badges
0
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;
}
answered Feb 26, 2015 at 5:10
I wouldn’t really class this as «AJAX». Anyway, something like following should do the trick:
document.body.style.backgroundColor = 'pink';
answered Oct 13, 2008 at 14:27
Duncan SmartDuncan Smart
30.6k9 gold badges66 silver badges70 bronze badges
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);
})
answered Nov 2, 2012 at 11:27
defau1tdefau1t
10.5k2 gold badges34 silver badges46 bronze badges
1
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.
Ozgur
3,70017 silver badges34 bronze badges
answered Sep 4, 2016 at 9:16
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;
answered Oct 13, 2008 at 14:48
redsquareredsquare
77.8k20 gold badges151 silver badges158 bronze badges
This will change the background color according to the choice of user selected from the drop-down menu:
function changeBG() {
var selectedBGColor = document.getElementById("bgchoice").value;
document.body.style.backgroundColor = selectedBGColor;
}
<select id="bgchoice" onchange="changeBG()">
<option></option>
<option value="red">Red</option>
<option value="ivory">Ivory</option>
<option value="pink">Pink</option>
</select>
answered Mar 25, 2017 at 11:39
Ritam DasRitam Das
1851 gold badge3 silver badges12 bronze badges
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";
});
answered Feb 22, 2018 at 11:14
AlexAlex
1634 silver badges11 bronze badges
<!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>
answered Apr 1, 2020 at 15:10
1
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)';
answered Nov 12, 2018 at 5:13
Divakar RajeshDivakar Rajesh
1,0822 gold badges19 silver badges22 bronze badges
Here are 2 ways to Change Background Color Using Javascript
-
To change background color with javascript you can apply
style.background
orstyle.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 usingstyle.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>
-
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 useclassList.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>
answered Aug 16, 2020 at 9:49
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>
answered Feb 1, 2011 at 17:41
james.garrissjames.garriss
12.7k6 gold badges82 silver badges95 bronze badges
so you can done very easily by just calling a function like
function changeBg()
{
document.body.style.color.backgroundColor="#ffffff";
}
answered Sep 29, 2021 at 6:55
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>
answered Jan 22, 2015 at 7:14
You can change background of a page by simply using:
function changeBodyBg(color){
document.body.style.background = color;
}
Read more @ Changing the Background Color
answered Mar 28, 2018 at 5:11
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);
answered Oct 2, 2013 at 19:27
It can be achieved using
document.body.style.color.backgroundColor="#000000";
answered Jun 23, 2022 at 8:27
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.❤
answered Feb 12, 2021 at 14:55
Kia BolukiKia Boluki
3073 silver badges14 bronze badges
<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>
answered May 3, 2021 at 18:41
1
Anyone know a simple method to swap the background color of a webpage using JavaScript?
Kevin Ji
10.4k4 gold badges39 silver badges58 bronze badges
asked Oct 13, 2008 at 14:23
0
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.
Mister Jojo
19k6 gold badges20 silver badges40 bronze badges
answered Oct 13, 2008 at 14:27
0
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.
answered Oct 13, 2008 at 14:27
Simon LehmannSimon Lehmann
10.6k4 gold badges41 silver badges53 bronze badges
2
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.
answered Oct 13, 2008 at 15:03
Martin KoolMartin Kool
4,1884 gold badges25 silver badges36 bronze badges
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";
answered Oct 13, 2008 at 14:30
OliOli
233k63 gold badges218 silver badges295 bronze badges
0
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;
}
answered Feb 26, 2015 at 5:10
I wouldn’t really class this as «AJAX». Anyway, something like following should do the trick:
document.body.style.backgroundColor = 'pink';
answered Oct 13, 2008 at 14:27
Duncan SmartDuncan Smart
30.6k9 gold badges66 silver badges70 bronze badges
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);
})
answered Nov 2, 2012 at 11:27
defau1tdefau1t
10.5k2 gold badges34 silver badges46 bronze badges
1
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.
Ozgur
3,70017 silver badges34 bronze badges
answered Sep 4, 2016 at 9:16
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;
answered Oct 13, 2008 at 14:48
redsquareredsquare
77.8k20 gold badges151 silver badges158 bronze badges
This will change the background color according to the choice of user selected from the drop-down menu:
function changeBG() {
var selectedBGColor = document.getElementById("bgchoice").value;
document.body.style.backgroundColor = selectedBGColor;
}
<select id="bgchoice" onchange="changeBG()">
<option></option>
<option value="red">Red</option>
<option value="ivory">Ivory</option>
<option value="pink">Pink</option>
</select>
answered Mar 25, 2017 at 11:39
Ritam DasRitam Das
1851 gold badge3 silver badges12 bronze badges
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";
});
answered Feb 22, 2018 at 11:14
AlexAlex
1634 silver badges11 bronze badges
<!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>
answered Apr 1, 2020 at 15:10
1
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)';
answered Nov 12, 2018 at 5:13
Divakar RajeshDivakar Rajesh
1,0822 gold badges19 silver badges22 bronze badges
Here are 2 ways to Change Background Color Using Javascript
-
To change background color with javascript you can apply
style.background
orstyle.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 usingstyle.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>
-
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 useclassList.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>
answered Aug 16, 2020 at 9:49
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>
answered Feb 1, 2011 at 17:41
james.garrissjames.garriss
12.7k6 gold badges82 silver badges95 bronze badges
so you can done very easily by just calling a function like
function changeBg()
{
document.body.style.color.backgroundColor="#ffffff";
}
answered Sep 29, 2021 at 6:55
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>
answered Jan 22, 2015 at 7:14
You can change background of a page by simply using:
function changeBodyBg(color){
document.body.style.background = color;
}
Read more @ Changing the Background Color
answered Mar 28, 2018 at 5:11
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);
answered Oct 2, 2013 at 19:27
It can be achieved using
document.body.style.color.backgroundColor="#000000";
answered Jun 23, 2022 at 8:27
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.❤
answered Feb 12, 2021 at 14:55
Kia BolukiKia Boluki
3073 silver badges14 bronze badges
<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>
answered May 3, 2021 at 18:41
1
Anyone know a simple method to swap the background color of a webpage using JavaScript?
Kevin Ji
10.4k4 gold badges39 silver badges58 bronze badges
asked Oct 13, 2008 at 14:23
0
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.
Mister Jojo
19k6 gold badges20 silver badges40 bronze badges
answered Oct 13, 2008 at 14:27
0
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.
answered Oct 13, 2008 at 14:27
Simon LehmannSimon Lehmann
10.6k4 gold badges41 silver badges53 bronze badges
2
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.
answered Oct 13, 2008 at 15:03
Martin KoolMartin Kool
4,1884 gold badges25 silver badges36 bronze badges
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";
answered Oct 13, 2008 at 14:30
OliOli
233k63 gold badges218 silver badges295 bronze badges
0
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;
}
answered Feb 26, 2015 at 5:10
I wouldn’t really class this as «AJAX». Anyway, something like following should do the trick:
document.body.style.backgroundColor = 'pink';
answered Oct 13, 2008 at 14:27
Duncan SmartDuncan Smart
30.6k9 gold badges66 silver badges70 bronze badges
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);
})
answered Nov 2, 2012 at 11:27
defau1tdefau1t
10.5k2 gold badges34 silver badges46 bronze badges
1
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.
Ozgur
3,70017 silver badges34 bronze badges
answered Sep 4, 2016 at 9:16
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;
answered Oct 13, 2008 at 14:48
redsquareredsquare
77.8k20 gold badges151 silver badges158 bronze badges
This will change the background color according to the choice of user selected from the drop-down menu:
function changeBG() {
var selectedBGColor = document.getElementById("bgchoice").value;
document.body.style.backgroundColor = selectedBGColor;
}
<select id="bgchoice" onchange="changeBG()">
<option></option>
<option value="red">Red</option>
<option value="ivory">Ivory</option>
<option value="pink">Pink</option>
</select>
answered Mar 25, 2017 at 11:39
Ritam DasRitam Das
1851 gold badge3 silver badges12 bronze badges
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";
});
answered Feb 22, 2018 at 11:14
AlexAlex
1634 silver badges11 bronze badges
<!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>
answered Apr 1, 2020 at 15:10
1
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)';
answered Nov 12, 2018 at 5:13
Divakar RajeshDivakar Rajesh
1,0822 gold badges19 silver badges22 bronze badges
Here are 2 ways to Change Background Color Using Javascript
-
To change background color with javascript you can apply
style.background
orstyle.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 usingstyle.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>
-
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 useclassList.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>
answered Aug 16, 2020 at 9:49
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>
answered Feb 1, 2011 at 17:41
james.garrissjames.garriss
12.7k6 gold badges82 silver badges95 bronze badges
so you can done very easily by just calling a function like
function changeBg()
{
document.body.style.color.backgroundColor="#ffffff";
}
answered Sep 29, 2021 at 6:55
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>
answered Jan 22, 2015 at 7:14
You can change background of a page by simply using:
function changeBodyBg(color){
document.body.style.background = color;
}
Read more @ Changing the Background Color
answered Mar 28, 2018 at 5:11
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);
answered Oct 2, 2013 at 19:27
It can be achieved using
document.body.style.color.backgroundColor="#000000";
answered Jun 23, 2022 at 8:27
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.❤
answered Feb 12, 2021 at 14:55
Kia BolukiKia Boluki
3073 silver badges14 bronze badges
<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>
answered May 3, 2021 at 18:41
1
Вы можете легко изменить цвет фона веб-страницы, то есть элемент <body>
или любой другой элемент динамически, используя его свойство style
в JavaScript.
Свойство style
используется для получения, а также для установки встроенного стиля элемента, например:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change the Background Color with JavaScript</title>
<script>
// Функция изменения цвета фона веб-страницы
function changeBodyBg(color){
document.body.style.background = color;
}
// Функция изменения цвета фона заголовка
function changeHeadingBg(color){
document.getElementById("heading").style.background = color;
}
</script>
</head>
<body>
<h1 id="heading">This is a heading</h1>
<p>This is a paragraph of text.</p>
<hr>
<div>
<label>Change Webpage Background To:</label>
<button type="button" onclick="changeBodyBg('yellow');">Yellow</button>
<button type="button" onclick="changeBodyBg('lime');">Lime</button>
<button type="button" onclick="changeBodyBg('orange');">Orange</button>
</div>
<br>
<div>
<label>Change Heading Background To:</label>
<button type="button" onclick="changeHeadingBg('red');">Red</button>
<button type="button" onclick="changeHeadingBg('green');">Green</button>
<button type="button" onclick="changeHeadingBg('blue');">Blue</button>
</div>
</body>
</html>
Читайте также
Похожие посты
Answer: Use the JavaScript width и height property You can use either width or height JavaScript property to proportionally increase и decrease the dimension of an image like zoom-in и zoom-out feature. Let’s take a look at the following example to understи how it basically works: Пример <!DOCTYPE html> <html lang=»en»> <head> <meta charset=»utf-8″> <title>JavaScript…
Вы можете просто использовать метод setTimeout(), чтобы сделать паузу, прежде чем продолжить выполнение кода в JavaScript. Время задержки выполнения скрипта указывается в миллисекундах (тысячных долях секунды). Давайте посмотрим следующий пример, чтобы понять, как это работает: Как вы заметили в предыдущем примере, JS-код после метода setTimeout() продолжает выполнение. Однако, если вам нужен настоящий «сон», когда все…
Самый простой способ перебрать массив в JavaScript — использовать цикл for. В следующем примере показано, как вывести все значения массива в JavaScript по очереди. В качестве альтернативы вы можете использовать недавно представленный цикл for-of в ES6 для итерации по массиву, например: См. Руководство по ES6-функциям JavaScript, чтобы узнать о новых функциях, представленных в ES6.
Смена цвета через js — мы можем поменять цвет, либо при наведении, либо при клике(onclick). разберем несколько способов менять цвет с помощью javascript.
Сменить цвет(background) при наведении мышки javascript
Для того, чтобы сделать сменяемость цвета с помощью javascript, при наведении мышки…Нам понадобится:
Нам понадобится элемент DOM div,
добавим style
+ width
+ height
+ background color
+ id
и получим:
<div style=»width:500px;height:100px;background:yellow» id=»example»></div>
javascript
Нам понадобится: script
+ onmouseover — когда мышка будет попадать на элемент,
И когда мышка будет покидать элемент — onmouseleave и внутри функций, в зависимости от действия будем изменять цвет, или возвращать первоначальный:
<script>
example.onmouseover = function() {
example.style.background= «red»;
};
example.onmouseleave = function() {
example.style.background= «yellow»;
};
</script>
Результат замены цвета при наведении мышки на элемент:
Изменить цвет(background) нажав по элементу.
В этом пункте разберем замену background цвета по клику с расположением js кода внутри тега.
Для того, чтобы изменить цвет элемента нажав по нему, нам понадобится, как и в выше проведенном пункте:
Пусть это будет элемент DOM div,
добавим style
+ width
+ height
+ background color
добавим onclick
и this,
Соберем это все в одн целое:
<div style=»width:500px;height:100px;background:yellow» onclick=»this.style.background=’red'»></div>
Результат замены цвета при клике на элемент:
Для того, чтобы увидеть изменение цвета элемента при нажатии на него нажмите по блоку!
Изменение цвета (background) javascript скриптом
Выше я уже рассмотрел один из вариантов изменения цвета (background) javascript внутри тега…
Теперь тоже самое(ну или похожее…) сделаем внутри скрипта…
Нам опять нужен элемент… + id
<div id=change_background>здесь background</div>
Обратимся к элементу через id
Стили для блока выделим в отдельный тег style
<style>
#change_background{width:500px;height:100px;background:yellow}
</style>
Далее скрипт изменения цвета (background) javascript скриптом
Используем один из способов onclick
Нам понадобится getElementById для получения объекта.
Ну и далее простое условие с проверкой, что внутри атрибута style , если цвет красный
if(if_id .style . background == «red»)
, то меняем его на #efefef
if_id .style . background = «#efefef»;
Во всех други случаях, т.е. иначе(else) меняем на красный…
if_id .style . background = «red»;
Скрипт javascript для замены background при нажатии
Не забываем… если не сделано onload, то скрипт должен находиться под выше приведенным кодом элемента, в котором собираемся изменить background при нажатии
<script>
document.addEventListener("click", function(e)
{
if_id = e . target. id;
if(if_id == "change_background")
{
if_id = document.getElementById(if_id);
if(if_id .style . background == "red")
{
if_id .style . background = "#efefef";
}
else
{
if_id .style . background = "red";
}
}
});
</script>
Пример изменения background при нажатии javascript
Нам остается разместить приведенный код прямо здесь. Чтобы проверить как работает изменение background при нажатии javascript кликните по ниже идущему цветному блоку…
здесь background
Изменение цвета кнопки (background) javascript
С помощью самописного скрипта, заставим кнопки менять цвет.
Алгоритм смены цвета кнопки.
У кнопки должно быть что-то одинаковое — «class» = click_me.
И что-то разное. уникальное, это id.
Пример кнопок:
<button class=»click_me» id=»id_1″>Измени цвет кнопки</button>
<button class=»click_me» id=»id_2″>Измени цвет кнопки</button>
<button class=»click_me» id=»id_3″>Измени цвет кнопки</button>
javascript
Возьмем один из способов onclick
document.addEventListener(«click», function(e)
Получим имена класса и ид:
if_id = e . target. id;
the_class = e . target.className;
Условие -если нажали по нашей кнопке с классом:
if(the_class == «click_me»)
Получаем объект из имени(которое получили раннее):
if_id = document.getElementById(if_id);
При покрашенной кнопке возвращаем нажатой кнопке её цвет по умолчанию:
if(if_id .style . background == «red»)
{
if_id .style . background = «#efefef»;
}
Иначе, всем кнопкам с классом возвращаем в цикле её цвет по умолчанию и только той кнопке, по которой нажали изменяем цвет::
else
{
var links = document.querySelectorAll(«.click_me»);
links.forEach(link => {
link.setAttribute(«style», «background:#efefef»);
})
if_id .style . background = «red»;
}
Соберем весь код смены цвета с помощью javascript
Html:
<button class="click_me" id="id_1">Измени цвет кнопки</button>
<button class="click_me" id="id_2">Измени цвет кнопки</button>
<button class="click_me" id="id_3">Измени цвет кнопки</button>
javascript
<script>
document.addEventListener("click", function(e)
{
if_id = e . target. id;
the_class = e . target.className;
if(the_class == "click_me")
{
if_id = document.getElementById(if_id);
if(if_id .style . background == "red")
{
if_id .style . background = "#efefef";
}
else
{
var links = document.querySelectorAll(".click_me");
links.forEach(link => {
link.setAttribute("style", "background:#efefef");
})
if_id .style . background = "red";
}
}
});
</script>
Результат изменения цвета при нажатии на элемент
- HowTo
- JavaScript Howtos
- Change the Background Color in …
Ammar Ali
Jul 24, 2021
This tutorial will discuss how to change the background color using the backgroundColor
property in JavaScript.
Change the Background Color Using the backgroundColor
Property in JavaScript
We can change the background color using the backgroundColor
property in JavaScript. To use this property, you need to get the element whose background color you want to change, and then you can use the backgroundColor
property to set the background color.
For example, let’s create a page using HTML and change the background color of the body to green using the backgroundColor
property. See the code below.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
document.body.style.backgroundColor = 'green';
</script>
</body>
</html>
You can also get the element with the id or name of the class. To get an element using its id, you can use the getElementById()
function. To get an element using its class, you can use the getElementsByClassName()
function.
For example, let’s get an element by its id and change its background color using the backgroundColor
property. See the code below.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id='myID'>
Hello Wold
</p>
<script type="text/javascript">
document.getElementById('myID').style.backgroundColor = 'green';
</script>
</body>
</html>
The code above will only change the background color of the element with id myID
and not the whole body section. You also change the background color of an element using the color code of different colors instead of changing it using the color name.
Let’s write a code to change the background color of a text using a button. See the code below.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onClick="Mycolor()">Change Color</button>
<div id="myID">Hello World</div>
<script type='text/javascript'>
function Mycolor() {
var element = document.getElementById("myID");
element.style.backgroundColor='#900';
}
</script>
</body>
</html>
In this code, you will see a button and a text. When you press the button, the background color of the text will change according to the given color.
Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.
LinkedIn
Facebook
Related Article — JavaScript Color
- RGB Color Model in JavaScript
- Convert RGB to HEX in JavaScript
2,247
There are a few ways you can change the background color of an HTML Element dynamically in JavaScript.
- Using style.backgroundColor property
- Using ClassList.add()
- Using setAttribute()
- Change background color of a div
- Change background color dynamically on button click
1. Using style.backgroundColor Property
You can use the style.backgroundColor property directly in JavaScript to change a background colour of an HTML element.
The below example will change the background color of the body element to red as soon as the HTML document loads on the browser.
This changes the background color of the entire page to red.
window.addEventListener('load', () => {
document.body.style.backgroundColor = 'red';
});
Try it out
See the Pen
Change Background Color Using JavaScript #1 by SoftAuthor (@softauthor)
on CodePen.
2. Using ClassList.add() Method
You can also change the background color of an HTML element by adding an external CSS rule which can be specified inside style tags or a separate CSS file.
In this case .bg-color{} which has a single property background-color:red;
.bg-color {
background-color:red;
}
Then, add the .bg-color class to the body HTML element when the page loads using the classList.add() method.
window.addEventListener("load", () => {
document.body.classList.add("bg-color");
});
This approach is cleaner than the first one because…now you can toggle the background color of the element by simply adding or removing the .bg-color CSS class.
Try it out
See the Pen
Change Background Color Using JavaScript #2 by SoftAuthor (@softauthor)
on CodePen.
3. Using setAttribute() method
Alternatively, you can also use the setAttribute() method to change the background color of the element instead of using the classList.add() method.
The setAttribute() method takes two arguments:
- Attribute name: class
- Attribute value: bg-color
window.addEventListener("load", () => {
document.body.setAttribute("class" , "bg-color");
});
Try it out.
See the Pen
Change Background Color Using JavaScript #3 – setAttribute() by SoftAuthor (@softauthor)
on CodePen.
4. Change Background Color Of A Div
Instead of changing the background color of an entire page, let’s change a div background color.
Here is a simple HTML markup.
index.html
<div id="box">
</div>
Here is the CSS style for the box element.
style.css
html, body {
height:100%;
display:flex;
justify-content:center;
align-items:center;
}
#box {
width:100px;
height:100px;
background:#32bacf;
}
.bg-color {
background-color:red;
}
Now change the background color of the box div element from blue color (#32bacf) that I’ve set inside #box CSS class to red colour using .bg-color CSS class inside JavaScript.
Inside the page load event, get a DOM reference of the div element using its id box.
const box = document.getElementById("box");
window.addEventListener("load", () => {
box.setAttribute("class", "bg-color"); // DON'T WORK
});
Unfortunatley, the above code won’t work...
That’s because when you add a different background color to id CSS selector and class CSS selector that are attached to the same HTML element, the background color specified inside the id CSS selector takes precedence.
Thats why the background color remains blue even after adding the .bg-color class to the element.
In this case, you need to use the style.backgroundColor property to override the background color specificed in the #box CSS selector.
window.addEventListener("load", () => {
box.style.backgroundColor = "red"; // IT WORKS
});
Try it out
See the Pen
Change Background Color Using JavaScript #3 – Div by SoftAuthor (@softauthor)
on CodePen.
5. Change Background Color On Button Click
Let’s create 4 buttons and have each represent a different color inside a div with an id button-group.
Change the background color of the page dynamically depending on which button is clicked using JavaScript.
<div id="button-group">
<button value="red">Red</button>
<button value="blue">Blue</button>
<button value="green">Green</button>
<button value="yellow">Yellow</button>
</div>
As you can see, each button has a value attribute with color name.
Use the value attribute to change the background color of the page on the button click.
* {
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color:grey;
}
#button-group {
background: black;
padding: 20px;
}
button {
padding: 10px;
font-size: 1.1em;
background: white;
color: black;
border: none;
border-radius: 10px;
border: 1px solid rgba(0, 0, 0, 0.2);
cursor: pointer;
}
button:hover {
background: rgba(255, 255, 255, 0.9);
}
Next, attach a click event to the button-group div element.
Check to see if the clicked element is a button.
If it is a button, change the background color of the body tag to the clicked button color, based on its value attribute.
You can get the value atribute from the event object – e.target.value.
const buttonGroup = document.getElementById("button-group");
const buttonGroupPressed = (e) => {
const isButton = e.target.nodeName === 'BUTTON';
if(!isButton) {
return
}
document.body.style.backgroundColor = e.target.value;
e.target.style.backgroundColor = e.target.value;
}
buttonGroup.addEventListener('click', buttonGroupPressed);
Finally, change the background color of the clicked button to the color that the button represents, again based on its value attribute.
Try it out
See the Pen
Change Background Color Using JavaScript #5 – On Click by SoftAuthor (@softauthor)
on CodePen.
When you want to change a webpage background color using JavaScript, you need to manipulate the document object model (DOM) property by calling it inside your <script>
tag.
The property you need to manipulate for changing the background color of the whole page is document.body.style.background
:
document.body.style.background = "red";
You can test the code out by changing the color of Google’s homepage. First, open your browser’s developer console. Then in the Console tab next to Elements, write the following code:
document.body.style.background = "orange";
The color of Google’s homepage will change to Orange, just like in the screenshot below:
Back when I first learned how to code, I used to do this to impress my non-coder friends. But inside your project, you probably want to trigger the color change when the visitors do something. For example, you can change the background color when a <button>
is clicked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript change background color</title>
<script>
// The function below will change the background color
function changeBackgroundRed() {
document.body.style.background = "red";
}
</script>
</head>
<body>
<h1>Click the button to change the background:</h1>
<button onclick="changeBackgroundRed();">Red</button>
</body>
</html>
Or you can also immediately change the background after the page is loaded by listening to the DOMContentLoaded
event as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript change background color</title>
<script>
// The function below will change the background color
function changeBackgroundRed() {
document.body.style.background = "red";
}
// call the function when the whole DOM content is loaded
document.addEventListener("DOMContentLoaded", changeBackgroundRed());
</script>
</head>
<body>
<h1>Change the background on load</h1>
</body>
</html>
The DOMContentLoaded
event is triggered when your whole HTML page has been loaded, even though some external JavaScript, CSS, and image resources are not yet fully loaded.
If you want to wait until the page and the resources are fully loaded, you can listen for the load
event instead.
Changing background color of a specific element
The document.body
code means you are selecting the <body>
tag of your HTML page. You can also change only a part of your page by selecting only that specific element.
The DOM provides several ways for you to select specific element:
getElementById()
— get a single element with matchingid
attributegetElementsByClassName()
— get elements with matchingclass
attributegetElementsByName()
— get elements with matchingname
attributegetElementsByTagName()
— get elements with matching tag name like"li"
for<li>
,"body"
for<body>
But the most recommended approach is to use getElementById()
because it’s the most specific of these methods. Out of the four methods, only getElementById()
will retrieve a single element.
The following example shows how you can change the background of <div>
element with id="user"
attribute:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript change background color</title>
<script>
// change the background color of div user
function changeBackgroundUser() {
document.getElementById("user").style.background = "red";
}
</script>
</head>
<body>
<div id="user">
<h1>Change specific DIV background color</h1>
</div>
<div id="guest">
<h2>This element's parent DIV background won't be changed</h2>
</div>
<div id="stranger">
<h2>Neither this one</h2>
</div>
<button onclick="changeBackgroundUser();">Red</button>
</body>
</html>
Finally, you can put the backgroundColor
as a parameter to the changeBackground()
function so that you can have buttons that change the background to different colors:
<script>
// change the background color using the passed parameter
function changeBackground(bgColor) {
document.body.style.background = bgColor;
}
</script>
<button onclick="changeBackground('red');">Red</button>
<button onclick="changeBackground('green');">Green</button>
<button onclick="changeBackground('blue');">Blue</button>
And that’s how you change the background color of a webpage with JavaScript.