How can I create a JavaScript function that checks my CSS code and changes the background color to #29fd53 if it is currently #222327? Likewise, how do I make it switch back to #222327 if the current background color is #29fd53?
This is my JavaScript code:
function changeBgC(){
var body = document.getElementsByTagName("body")[0];
var computedStyle = window.getComputedStyle(body)
var bodyBackgroundValue = computedStyle.getPropertyValue("background-color")
console.log(bodyBackgroundValue);
if (bodyBackgroundValue == "#222327") {
document.querySelector('body').style.backgroundColor = "#29fd53"
} else {
document.querySelector('body').style.backgroundColor = "#222327"
}
}
.body{
width: 100%;
height: 100vh;
min-height: 100vh;
background: #222327;
}
<div class="box">
<button onclick="changeBgC()" class="menuButton">≣</button>
</div>
I tried using i++ in my code (by adding an onclick event in my HTML) but it only changes the background color to #29fd53. Pressing the button again doesn't trigger any change.
Here's what I attempted:
function changeBgC(){
var i = 0
if (i % 2 === 0){
document.querySelector('.body').style.backgroundColor = "#29fd53"
console.log(i);
i+=1
}else{
document.querySelector('.body').style.backgroundColor = "#222327"
i+=1
}
}