How to select multiple buttons and keep the border on each one clicked?

Viewed 57

So we have 4 buttons and when we click on one it gets a black border but when you click another button the previous button loses its border and the new one gets it.

const btnPlaces = document.querySelectorAll('.btn-places');

for (let i = 0; i < btnPlaces.length; i++) {
  btnPlaces[i].addEventListener("click", function(e) {
    let prevBtn = document.querySelector(".checked");
    if (prevBtn) {
      prevBtn.classList.remove("checked");
      e.target.classList.add("checked");
    } else {
      e.target.classList.add("checked");
    }
  });
}
.checked {
  border: 3px solid rgb(34, 34, 34);
}
<button class="btn-places" id="berlin">BERLIN</button>
<button class="btn-places" id="netherlands">NETHERLANDS</button>
<button class="btn-places" id="sweden">SWEDEN</button>
<button class="btn-places" id="italy">ITALY</button>

Is there an alternative solution that is more efficient?

3 Answers

You can use :focus state in CSS. Only one element is active at the time with :focus state.

.btn-places:focus {
  border: 3px solid rgb(34, 34, 34);
}
<button class="btn-places" id="berlin">BERLIN</button>
<button class="btn-places" id="netherlands">NETHERLANDS</button>
<button class="btn-places" id="sweden">SWEDEN</button>
<button class="btn-places" id="italy">ITALY</button>

It sounds like you're trying to keep the button border even when another is clicked. In that case, you would need to remove:

prevBtn.classList.remove("checked");

from your condition.

const btnPlaces = document.querySelectorAll('.btn-places');

for (let i = 0; i < btnPlaces.length; i++) {
  btnPlaces[i].addEventListener("click", function(e) {
    let prevBtn = document.querySelector(".checked");
    if (prevBtn) {
      e.target.classList.add("checked");
    } else {
      e.target.classList.add("checked");
    }
  });
}
.checked {
  border: 3px solid rgb(34, 34, 34);
}
<button class="btn-places" id="berlin">BERLIN</button>
<button class="btn-places" id="netherlands">NETHERLANDS</button>
<button class="btn-places" id="sweden">SWEDEN</button>
<button class="btn-places" id="italy">ITALY</button>

Related