简体   繁体   中英

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.

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>

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM