samedi 29 février 2020

JS switch onlick between two colors w/ if else

I'm working on my portfolio and need to switch between to stylings states of an element. Currently, I'm trying to make it work on the following example. In this particular case, my goal is to click the button and switch between green and red background with every click. But something won't work. I can switch from green to red, but not from red to green. What am I missing?

<button id="button">Toggle</button>
<div class="test" id="test"></div>


.test {
  width: 100px;
  height: 100px;
  background: green;
  margin-top: 20px;
}


var btn = document.getElementById("button");
var test = document.getElementById("test");

btn.onclick = function() {
  if (test.style.background = "green") {test.style.background = "red";} else {test.style.background = "green";}};

Codepen Demo https://codepen.io/yanniksturm/pen/rNVmqJe

Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire