Skip to main content

JavaScript – Change Body Background Color to Different Colors on Button Click

Submitted by admin on Mon, 06/06/2022 - 21:20

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() { = colors[count];
  if (count < colors.length - 1) {
  } else {
    count = 0;


Demo - Change Body Background Color on click using JavaScript


Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.