DEV Community

Oliwier965
Oliwier965

Posted on • Edited on

Multiple buttons only one active on click

Today I want to share with you how to do an effect, that if you have multiple buttons and you want to add active styling class on click but when you click on other button remove active class from last button and add it to the latest clicked. Interested so let's get into it. Here's how to accomplish it.

1 Select all buttons. I named my variable btnsTip and selected them through data attribute, but it's up to you.
const btnsTip = document.querySelectorAll("[data-btn-tip]");

2 Add variable where we'll be storing last clicked button and set its value to null.
let activeBtn = null;

3 Loop through them and for each, create event listener on click and put event (e) in the parentheses to access it later.

btnsTip.forEach((btnTip) => {
  btnTip.addEventListener("click", (e) => {
  });
});
Enter fullscreen mode Exit fullscreen mode

4 Do check if active button isn't equal to null because if it was, that will mean that there's no element stored because it's default variable value, and isn't equal to current target because we don't want to remove class on double click on current element. And we remove active class from our variable that mean that we remove active class from our last element.

btnsTip.forEach((btnTip) => {
  btnTip.addEventListener("click", (e) => {

    //New code here
    if ((activeBtn === null && activeBtn !== e.currentTarget)) {
      activeBtn.classList.remove("active");
    }
    //

  });
});
Enter fullscreen mode Exit fullscreen mode

5 And last step we add active class to current element and set our activeBtn variable to current element that we have clicked.

btnsTip.forEach((btnTip) => {
  btnTip.addEventListener("click", (e) => {

    //New code here
    e.currentTarget.classList.add("active");
    //

    if ((activeBtn === null && activeBtn !== e.currentTarget)) {
      activeBtn.classList.remove("active");
    }

    //New code here
    activeBtn = e.currentTarget;
    //

  });
});
Enter fullscreen mode Exit fullscreen mode

Full Code Down Bellow

const btnsTip = document.querySelectorAll("[data-btn-tip]");
let activeBtn = null;

btnsTip.forEach((btnTip) => {
  btnTip.addEventListener("click", (e) => {
    e.currentTarget.classList.add("active");

    if ((activeBtn === null && activeBtn !== e.currentTarget)) {
      activeBtn.classList.remove("active");
    }

    activeBtn = e.currentTarget;
  });
});
Enter fullscreen mode Exit fullscreen mode

If you liked my post or was it useful to you, Like, Share, and Comment :)

Top comments (1)

Collapse
 
kostyantyn94 profile image
kostyantyn94

Hi, it worked fot me only when I turned this

if ((activeBtn === null && activeBtn !== e.currentTarget)) {
activeBtn.classList.remove("active");

to this:

if ((activeBtn != null && activeBtn !== e.currentTarget)) {
activeBtn.classList.remove("active");

Thanks!