My button don’t toggle itself

Hello everybody I have a problem with my code, for some reason I cannot make my div box be with a lightblue backgroundcolor change to purple when I click on the button and change from purple to lightblue when I click again

https://codepen.io/josemon322/pen/mdbRBeK

HTML

<button onclick="myFunction()">Default Button</button>
<div id="myBox">
	
</div>

CSS

button {
	display: block;
	margin: 5px;
}
#myBox {
	margin: 5px;
	display: block;
	height: 150px;
	width: 250px;
        background-color: lightblue;
}
.light-blue {
  background-color: lightblue;
}

.purple {
  background-color: purple;
}
JS

function myFunction() {  
  // Define myBox div
  const myDiv = document.querySelector("#myBox");
  
  // Do a check to see which color class myDiv    contains
	if (myDiv.classList.contains("light-blue")) {
	 // Remove light blue class
    myDiv.classList.remove("light-blue");
    // Add purple class
    myDiv.classList.add("purple");
	} 
	else if(myDiv.classList.contains("purple")) { 
	  // Remove purple class 
    myDiv.classList.remove("purple");
    // Add light-blue class
    myDiv.classList.add("light-blue")
    }
}

Hi @charlms350, there’s no class is set initially on the box so neither condition in the click handler will be true. So you’ll either have to give the box an initial class, or make the else if a simple else so that will become the default action.

1 Like