Skip to content
Advertisement

Toggle button background color when clicked

I have this function, intended to toggle the background between two predefined colors of a button each time it is clicked:

const showAvailButtonClicked = (targetButton, clickedColor, unClickedColor) => {
  let clickedElement = document.getElementById(targetButton)
  let currColor = clickedElement.style.backgroundColor
  if (currColor == clickedColor) {
    clickedElement.style.backgroundColor = unClickedColor
  } else {
    alert("Current color:" + currColor)
    clickedElement.style.backgroundColor = clickedColor
  }
}

let targetButton = document.getElementById("testbutton")
targetButton.addEventListener("click", () => {
  showAvailButtonClicked("testbutton","#ba0202", "#0f2e0c")
})
#testbutton {
  background-color: #0f2e0c;
}
<button id="testbutton">Toggle</button>

I encounter two issues with this simple code above:

1 – The button starts out with this color unClickedColor = #0f2e0c. However, on the very first click, the alert does not register any color. ie. the alert message shows Current color: only.

2 – On the 2nd and subsequent clicks, the registered color from this line let currColor = clickedElement.style.backgroundColor gives RGB format rgb(r, g, b). How do I force it into hexadecimal format so that I can make the color comparison? Thanks.

Advertisement

Answer

Far better off to attach a class to the button on the click and have the styling on that class.

The following snippet has the base background color set for the button and then when its clicked – toggles a”clicked” class – that when applied – provides an alternate background color.

This is simpler to implement because you are not having to determine the existing background color followed by some funky hex comparison and also its much better to separate the html, js and css into their own realms.

let testButton = document.getElementById("testbutton");

testButton.addEventListener("click", () => {
  testButton.classList.toggle('clicked');
})
#testbutton {
  background-color: #0f2e0c;
  color: white
}

#testbutton.clicked {
  background-color: #ba0202;
}
<button id="testbutton">Toggle</button>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement