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

Home Forums Support [Resolved] Proper Way to Set Mobile Menu to Collapse After Selecting An Anchor Link

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

  • This topic has 3 replies, 2 voices, and was last updated 2 months ago by Elvin.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2008472
    Brent Wilson

    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

    #2008627
    Elvin
    Staff
    Customer Support

    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>

    A wise man once said:
    "Have you cleared your cache?"

    #2008658
    Brent Wilson

    That seems to have worked! Thanks!

    Brent

    #2008709
    Elvin
    Staff
    Customer Support

    No problem. Glad you got it sorted. 😀

    A wise man once said:
    "Have you cleared your cache?"

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.