I’m trying to create a button whose change background color (to green) when it is cliked. But when it is cliked againg the button returns to the original background color (from orange).
var btn1 = document.getElementById("btn-1")
if (btn1.style.backgroundColor = "orange") {
btn1.addEventListener("click", function () {
btn1.style.backgroundColor = "green"
})
} else {btn1.addEventListener("click", function () {
btn1.style.backgroundColor = "orange"
})
}
Could you help me? Thx!
I’m trying to create a button whose change background color (to green) when it is cliked. But when it is cliked againg the button returns to the original background color (from orange).
3
Answers
There are many ways to do this. My preferred way is simply toggle a class on the element.
In CSS set the default color via #btn-1 then have an active color set via #btn-1.active. Then by toggling the class of active, you change the color to green when the element has the class of active, and orange when it doesn’t.
Just toggle the color on the click event:
how i understand you: you can set starter color of button to orange;
and then add EventListener to button with this logic:
-if the color of the button is
orange
– change togreen
or if the color is not
orange
– change toorange