hello I have been trying to make this button toggle to the original color “lightBlue” after becomes “purple” clicking on it but nothing is working
https://codepen.io/josemon322/pen/mdbRBeK
<button onclick="myFunction()">Default Button</button>
<div id="myBox">
</div>
button {
display: block;
margin: 5px;
}
#myBox {
margin: 5px;
display: block;
height: 150px;
width: 250px;
}
var box = document.getElementById("myBox").style.backgroundColor = "lightBlue";
function myFunction() {
if (box == 'lightBlue') {
document.getElementById("myBox").style.backgroundColor = "purple";
}
else {
document.getElementById("myBox").style.backgroundColor = "lightBlue";
}
}
The easiest way to go about this is to originally set the color of #myDiv to light-blue through a class, so basically have a light-blue class on myDiv, then separately have another class for the color purple, and on your click function you’ll simply do a check on myDiv to see what color it is, basically how you have it now.
But instead of defining the styles directly onto the div, you would want to add / remove the corresponding color classes each time the button is clicked. Below is what I have mocked up which gives it that effect.
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")
}
}
CSS
.light-blue {
background-color: lightBlue;
}
.purple {
background-color: purple;
}
1 Like