I want it to change color when the button is clicked and I implement it in code. But how can I make the button change to the original color when pressed again? So I want the button to turn black when clicked and white again when clicked again.
let pushButtons = document.querySelectorAll('.card__itemsize')
pushButtons.forEach( pushButton =>
{
pushButton.addEventListener('click', (e) =>
{
if (e.target === pushButton)
{
pushButton.classList.add('clickSizeBlack')
}
})
})
2
Answers
You need to add else statement as if the
button
hasclickSizeBlack
class, then remove theclickSizeBlack
class and addclickSizeWhite
class to that button.Otherwise always add
clickSizeBlack
class.Basically what you’re trying to achieve is the button to toggle switching between two states(pressed and not pressed) which will be represented by the given colors(white and black).
The toggle method will allow you to add a class if it’s not present and remove it if it’s already present. In your case, you want to toggle between clickSizeBlack and the original class of the button.