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.