Answer the question
In order to leave comments, you need to log in
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");
}
});
Answer the question
In order to leave comments, you need to log in
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')
});
});
document.addEventListener('click', removeAllActive)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question