Select ONE button. Deselect other buttons

I am trying to select a navigation button and deselect other:

https://jsfiddle.net/gkfm07u8/24/

This selects when you click on one button, but does not deselect others:

  btn.addEventListener('click', () => {
    btn.classList.add("active");
  });

This deselects the button “manually”

  btn.addEventListener('click', () => {
    btn.classList.toggle("active");
  });

What I am looking for is a “deselect other” function. Pseudocode:

  btn.addEventListener('click', () => {
    btn.classList.add("active");
    } else {
    btn.classList.add("");
  });

What is the correct syntax.

Bearing in mind I’m a beginner at JS also so there probably is a more concise way of doing this then I would remove all the active classes from the buttons and then add the active class to the currently clicked button.

e.g.

const btns = document.querySelectorAll('.btn');
const subnav = document.querySelector('.subnav');

btns.forEach((btn) => {
  btn.addEventListener('click', () => {
    removeClasses();
    addClasses(btn);
  });
});

function removeClasses() {
  btns.forEach((btn) => {
    btn.classList.remove("active");
    subnav.classList.remove('open');
  });
}

function addClasses(btn) {
  btn.classList.add("active");
  subnav.classList.add('open');
}

As I said JS is not my forte and one of the gurus here will soon put me right :slight_smile:

2 Likes

Paul’s pretty much got it, though it can be streamlined a little since you’re walking through all the buttons anyway, might as well combine the two into a single function call…

function removeClasses(target) {
  btns.forEach((btn) => {
    if(btn == target) { btn.classList.add("active"); }
    else { btn.classList.remove("active"); }
  });
}
2 Likes

Thank you both! If I interpret this correct, there is no options but loop twice?

Well two loops, executed at different times; one to attach the listener to all of your buttons, and the other when someone clicks on said button.