Is there a way to switch the background style of a CSS div when clicking the same button?
function changeBg() {
var divElem = document.getElementById("change-bg");
if (divElem.style.backgroundColor === "yellow") {
divElem.style.backgroundColor = "red";
} else {
divElem.style.backgroundColor = "yellow";
}
}
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>
Currently, it changes color to red. How can I make it revert back to its original color (yellow) when clicking the same button?
Feel free to explore the JSFiddle.
I believe an If-Else
statement could solve this issue. However, I am having trouble implementing it.