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.
1 | <button type="button" id="bg-button" onclick="changeBg()">Change Body Background Color</button> |
JavaScript Code
1 2 3 4 5 6 7 8 9 10 11 12 | 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; } } |
Demo
Demo – Change Body Background Color on click using JavaScript