skip to Main Content

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


  1. You need to add else statement as if the button has clickSizeBlack class, then remove the clickSizeBlack class and add clickSizeWhite class to that button.
    Otherwise always add clickSizeBlack class.

    
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            if (button.classList.contains('clickSizeWhite')) {
                button.classList.remove('clickSizeWhite');
                button.classList.add('clickSizeBlack');
            } else if (button.classList.contains('clickSizeBlack')) {
                button.classList.remove('clickSizeBlack');
                button.classList.add('clickSizeWhite');
            } else {
                button.classList.add('clickSizeWhite');
            }
        });
    });
    
    Login or Signup to reply.
  2. 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).

    let pushButtons = document.querySelectorAll('.card__itemsize');
    
    pushButtons.forEach(pushButton => {
      pushButton.addEventListener('click', (e) => {
        if (e.target === pushButton) {
          pushButton.classList.toggle('clickSizeBlack');
        }
      });
    });
    

    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.

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