26 Dec 2023
![JavaScript Change Body Background Color](/sites/default/files/styles/wide/public/2023-12/body-background-on-click.jpg?itok=jkLPeDQm)
In this JavaScript tutorial we will create a button that will change the background color of body to different colors on a button click.
Create a Button
Let's first create a button which will call a JavaScript function changeBg() on click.
<button type="button" id="bg-button" onclick="changeBg()">Change Body Background Color</button>
JavaScript Code
let count = 0;
const bgButton = document.querySelector("#bg-button");
const bodyBg = document.querySelector("body");
let colors = ['Aqua', 'Coral', 'pink', 'LightGreen', 'Orange', 'Silver'];
function changeBg() {
bodyBg.style.background = colors[count];
if (count < colors.length - 1) {
count++;
} else {
count = 0;
}
}
- Log in to post comments