Skip to content
Advertisement

How do I show a selected button in a row by changing CSS in an HTML site?

I have a div of buttons in line and I want the user to be able to see when they selected a button by changing the CSS and it only going back to its old state when they select another button. Is this possible?

Advertisement

Answer

Find all the buttons and add event listener to execute some javascript where you put the logic of changing the behaviour of the buttons.

// Find all the buttons through their class names
buttons = document.querySelectorAll(".btn")

// loop through all the buttons
for (let i = 0; i < buttons.length; i++) {
  let button = buttons[i];
  
  // Add click event to buttons
  button.addEventListener("click", function() {
     
    // First remove 'clicked' class from all buttons
    buttons.forEach(function(item){
      item.classList.remove("clicked");
    })
    
    // Next add 'clicked' class to clicked button
    button.classList.add("clicked");
  });
}
/* class added through javascript to the buttons to change appearance of clicked
 buttons */
.clicked {
  background-color: coral;
}
<div>
  <button type="button" class="btn">A</button>
  <button type="button" class="btn">B</button>
  <button type="button" class="btn">C</button>
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement