Automattic / _s

Hi. I'm a starter theme called _s, or underscores, if you like. I'm a theme meant for hacking so don't use me as a Parent Theme. Instead try turning me into the next, most awesome, WordPress theme out there. That's what I'm here for.
http://underscores.me/
GNU General Public License v2.0
10.96k stars 3.12k forks source link

Clicking outside mobile navigation doesn't close it #1375

Closed kangabell closed 4 years ago

kangabell commented 5 years ago

When the navigation menu is open you can close it by clicking the "menu" toggle button, but I'd like to also be able to close it when clicking outside of it. Is there a way to do this without completely rewriting the js functionality on this nav?

kangabell commented 5 years ago

Update for anyone else looking to do this. I was able to accomplish this with the following:


    document.addEventListener("click", function(evt) {
        targetElement = evt.target;  // clicked element

        do {
            if (targetElement == container) {
                return;
            }
            targetElement = targetElement.parentNode;
        } while (targetElement);

        container.className = container.className.replace( ' toggled', '' );
        button.setAttribute( 'aria-expanded', 'false' );
        menu.setAttribute( 'aria-expanded', 'false' );
    });```
GitarMan commented 4 years ago

This has been a complaint of mine and my clients as well.

Below has been my similar solution that uses the existing container variable:

    // Close small menu when user clicks outside nav container
    document.addEventListener('click', function(event) {
        var isClickInsideNav = container.contains(event.target);

        if (!isClickInsideNav) {
            container.className = container.className.replace( ' toggled', '' );
            button.setAttribute( 'aria-expanded', 'false' );
            menu.setAttribute( 'aria-expanded', 'false' );
        }
    });

This seems like a general enough issue that I was thinking of submitting a pull request.

I have not contributed to this project yet so I don't know the protocol, but this is something that I add to all my new projects now and I would guess that others would like the same.