How to toggle CSS style on-click same button in JS?

How to toggle CSS div background style on clicking the same button?

function changeBg() {
  var divElem = document.getElementById("change-bg");
  divElem.style.backgroundColor = "red";
}
body {
  margin: 0;
}

#change-bg {
  /* Extra Text Formatting */
  padding: 10px;
  text-align: center;
  /* Primary Background Color */
  background-color: yellow;
}
<div id="change-bg">
  <h3>
    Hello World
    <br/>
    <button onclick="changeBg();">Change Color</button>
  </h3>
</div>

It Changes color to red, but how do I revert its original color (yellow) on clicking the same button

Check out the JSFiddle. I think It can be solved using If-Else, I’m not able to implement it.

Answer

Here’s an alternative with a toggle variable and the if-else solution mentioned in the OP.

const divElem = document.getElementById("change-bg");
let toggle = true;

function changeBg() {
  divElem.style.backgroundColor = toggle ? 'red' : 'yellow'
  toggle = !toggle;
}
body {
  margin: 0;
}

#change-bg {
  padding: 10px;
  text-align: center;
  background-color: yellow;
}
<div id="change-bg">
  <h3>
    Hello World
    <br/>
    <button onclick="changeBg();">Change Color</button>
  </h3>
</div>
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .