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

Time:12-02

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

You can use classList.toggle to change class name string and change it back when classList already has with this following code

const box = document.querySelector(".bg")
const btn = document.querySelector(".btn")

btn.addEventListener("click", () => {
  box.classList.toggle("blue")
})
.bg{
  background: red;
  width: 100px;
   height: 100px;
}

.blue{
  background: blue
}
<div class="bg"></div>
<button class="btn">Toggle it</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use This Methhod as it is:)

function changeBg() {
  var divElem = document.getElementById("change-bg");
  divElem.classList.toggle("change-color");
}
body {
  margin: 0;
}

#change-bg {
  /* Extra Text Formatting */
  padding: 10px;
  text-align: center;
  /* Default Background Color */
  background-color: yellow;
}
.change-color{
  background-color: red !important;
}
<!DOCTYPE html>

<head>
</head>

<body>
  <div id="change-bg">
    <h3>
      Hello World
      <br/>
      <button onclick="changeBg();">Change Color</button>
    </h3>
  </div>
</body>

</html>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related