Anyone know a simple method to swap the background color of a webpage using JavaScript?
You can change background of a page by simply using:
function changeBodyBg(color){
document.body.style.background = color;
}
Read more @ Changing the Background Color
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";
});
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.
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 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;