Hi, I’m stuck with a website menu I’m building at the moment. This is my code so far:
const megamenu = document.querySelector('.megamenu');
const menuSection = megamenu.querySelector('.megamenu-section');
const submenus = document.querySelectorAll('.megamenu-submenu');
menuSection.addEventListener('click', (e) => {
e.preventDefault();
submenus.forEach(submenu => {
if (submenu.classList.contains('active')) {
submenu.classList.remove('active');
console.log("hasActive")
} else {
console.log("hasNoActive")
}
})
e.target.closest('.megamenu-submenu').classList.toggle('active');
});
I’m adding “.active” class to the first level link of the menu to open the corresponding submenu.
However, what I still need is a way to toggle the “.active” class if the currently active first level link is clicked again so that the open submenu closes.
I think I need a way to check if the active menu has the class “.active” and if yes, close the menu. I guess the problem is in the forEach because here I first remove all “.active” classes because otherwise the submenu of each link would stay open even if a different first level link was clicked.
I can’t think of a solution for this problem. Any help would be highly appreciated.
Thanks a lot.