D
D
Dallas152021-06-27 13:29:17
JavaScript
Dallas15, 2021-06-27 13:29:17

How to use JS when clicking on buttons with the same classes to remove the active class from another button, add only to the pressed button?

Good afternoon. Need help. I'm a layout designer, I'm doing a test task. I need to do something in JS, but I haven’t learned JS yet, so I can’t solve the problem myself. The essence of my problem: there are buttons on the site that, when clicked, open dropdowns. Each button has its own drobdown. The task is to make it so that when clicking anywhere except the dropdown itself, the active class is deleted from the parent of the button or the menu itself, it doesn’t matter and the menu closes. Ready-made solutions work, they close the dropdown when clicking outside the menu, but the problem is that there are 6 buttons that open the menu, with the same classes, and when one menu is open, when you click on another button, another 1 menu opens, and the already open one does not close. I found a code that added active as needed, only 1 element, but did not delete it when clicking on an empty space. Now I'm using the following code, which I found here

$(".dropdown__btn").click(function (event) {
  event.preventDefault();
  $(this).parent().toggleClass("active");
  return false;
});

$(document).click(function (e) {
  if (!$(e.target).closest(".dropdown__menu").length) {
    $(".dropdown__menu").parent().removeClass("active");
  }
});


Here you can see the HTML code https://codepen.io/dallas1510/pen/NWjKMpG . Styles flew off, but the essence, I think, is clear.
Thanks for the advice

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
szQocks, 2021-06-28
@Dallas15

const dropDownBtns = document.querySelectorAll('.dropdown__btn');
const dropDowns = document.querySelectorAll('.filter__dropdown');

const removeAllActive = () => {
  return dropDowns.forEach(item => item.classList.remove('active'));
};

dropDownBtns.forEach(btn => {
  btn.addEventListener('click', async (e) => {
    await removeAllActive();
    e.target.parentNode.classList.add('active')
  });
});

There it would be necessary to make an overlay, and catch a click on it and not on the entire document. But for now, try this code that I wrote to you. And do not forget to remove functions from all buttons when clicking like myFunction1() myFunction2() etc.
document.addEventListener('click', removeAllActive)

first check the code that the first one wrote, if everything is ok, then try to add it, but I think that the menus will all close on any click somewhere, so you can’t do without an overlay.
Then, if you make an overlay or buttons for closing dropdowns, I'll add the Js code for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question