26 Dec 2023
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