0

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 Answers3

2

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.

var toggleBTN = document.getElementById("btn-1")

toggleBTN.addEventListener("click",() => {
  toggleBTN.classList.toggle("active");
});
#btn-1{
  background:orange;
}

#btn-1.active{
  background:green;
}
<button id="btn-1">Toggle Color</button>
imvain2
  • 15,480
  • 1
  • 16
  • 21
1

Just toggle the color on the click event:

document
  .getElementById("btn-1")
  .addEventListener(
    'click', 
    ({target:{style}}) => style.backgroundColor = style.backgroundColor === 'orange' ? 'green' : 'orange'
  );
<button id="btn-1" style="background-color: orange">Click me</button>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17
  • You should always explain your answer. Don't assume the OP or future visitors will understand what you did without one. – j08691 Jun 01 '23 at 19:12
0

let button = document.getElementById("button");
    button.style.backgroundColor = "orange";

button.addEventListener("click", function () {
        if(button.style.backgroundColor == "orange"){
           button.style.backgroundColor = "green";
        } else button.style.backgroundColor = "orange";
})
<button id="button">test</button>

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 to green
or if the color is not orange - change to orange

bazylevnik0
  • 60
  • 1
  • 7