How can I change this button background color of the specific button that i have clicked? using javascript

Issue

I want to change the button’s background color of the specific button that I have clicked, do I need to use loops and also condition? I tried to access the first index but I don’t know how can I change the other button’s background color.

let buttons = document.querySelectorAll('.btn');

let arraySelected = [];

buttons.forEach(button => {
  button.addEventListener('click', seatFunction);
});


function seatFunction(e) {

  const {
    value
  } = e.target;
  let newArray = arraySelected;
  const index = arraySelected.findIndex((element) => element === value);

  let findValue = arraySelected.find((element) => element == value);

  if (index !== -1) {
    console.log(`The ${value} has been removed into the array.`);
    // console.log(`The ${index} is the '${value}' of the item that has been removed.`);    
    newArray.splice(index, 1);
    console.log(newArray);
    buttons[0].style.backgroundColor = null;

  } else {
    console.log(`${value} has been pushed into the array.`)
    arraySelected.push(value);
    console.log(arraySelected);
    buttons[0].style.backgroundColor = "red";

  }

  // Checking if the array is empty.
  if (arraySelected.length === 0) {
    alert(`The last value '${value}' has been removed\r\nThe array now is empty!`);

  }
}
<div class="wrapper">
  <button class="btn seat" value="A">A</button>
  <button class="btn seat" value="B">B</button>
  <button class="btn seat" value="C">C</button>
  <button class="btn seat" value="D">D</button>
  <button class="btn seat" value="E">E</button>
  <button class="btn seat" value="F">F</button>
</div>

Solution

You’re approaching it the right way. You just need to loop over all the buttons and reset their background, and then change the background of the button you clicked on.

I’m using classList and CSS for this example.

const buttons = document.querySelectorAll('.btn');

buttons.forEach(button => {
  button.addEventListener('click', seatFunction, false);
});

function seatFunction() {
  buttons.forEach(btn => btn.classList.remove('active'));
  this.classList.add('active');
}
.active { background-color: Tomato; }
.btn:hover { cursor: pointer; }
<div class="wrapper">
  <button class="btn seat" value="A">A</button>
  <button class="btn seat" value="B">B</button>
  <button class="btn seat" value="C">C</button>
  <button class="btn seat" value="D">D</button>
  <button class="btn seat" value="E">E</button>
  <button class="btn seat" value="F">F</button>
</div>

Answered By – Andy

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.