Menu with submenu panels: How to close the submenu panel if the currently active link was clicked?

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.

I think you will have to post the HTML so we can understand the structure of the menu. Better yet, post a live example on Codepen.

I’m pretty sure I’m not able to fully visualize what you are doing here just based on the JS, but it does sound like one class might not be enough. You can also use data attributes to describe the state in the DOM. So they are not used to style anything just to contain any state that you then can check for in the JS.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.