Anyone know a simple method to swap the background color of a webpage using JavaScript?
This is simple coding for changing background using javascript
<body onLoad="document.bgColor='red'">
<!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>
I wouldn't really class this as "AJAX". Anyway, something like following should do the trick:
document.body.style.backgroundColor = 'pink';
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>
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
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.