skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search