Site logo

Archived topic

Proper Way to Set Mobile Menu to Collapse After Selecting An Anchor Link

3 replies · Started by Brent Wilson on November 17, 2021

Viewing posts 1–4 of 4

I have a menu with several anchor links (for a one-page style of website). In screen widths where the hamburger menu shows, clicking on the hamburger icon of course expands the menu options. But when I select one of the anchor links, the menu stays expanded. If a site visitor were to scroll back up to the top of the page, the mobile menu would still be visible in its expanded state. I want it to automatically collapse after selecting an anchor link. What is the best way to achieve this? So this Loom video for a quick walkthrough of the issue: https://www.loom.com/share/77755b6462bc40dcad2d0b5e40680b9c

Hi Brent,

We can try a script for that.

You can hook this on your site's wp_footer using a Hook element.

<script>
const HtmlTag = document.querySelector('html');

const PrimaryMenu = document.querySelector('nav#site-navigation');

const MobileMenuCtrlWrap = document.querySelector('nav#mobile-menu-control-wrapper');

const MenuElement = document.querySelector('ul#menu-main-menu');

let PrimaryMenu_btns = MenuElement.querySelectorAll('li.menu-item > a');

function dbHandleClick(evt) {
    for (var y = 0; y < PrimaryMenu_btns.length; y++) { 
        if ( PrimaryMenu_btns[y] == evt.target ) {
            HtmlTag.classList.remove('mobile-menu-open');
            MobileMenuCtrlWrap.classList.remove('toggled');
            PrimaryMenu.classList.remove('toggled');
            MenuElement.setAttribute('aria-hidden','true')
        }
    }
}

window.addEventListener("click", dbHandleClick);
</script>

That seems to have worked! Thanks!

Brent

No problem. Glad you got it sorted. :D

This archived topic is closed to new replies.