Site logo

Archived topic

Auto close mobile menu when scrolling

11 replies · Started by Nick on February 20, 2021

Viewing posts 1–12 of 12

Hi team -

Is there a way to autoclose the mobile menu when you start to scroll on a page?

To demonstrate, load the page below on a mobile device then click the hamburger icon. If you then start to try and scroll on the page, I would like the menu to auto-close (in the same way as when you click the X button).

thanks, Nick

Hi there,

This could open a can of worms, but in its simplest form you should be able to do something like this:

document.addEventListener( 'scroll', function( e ) {
    var openedMenus = document.querySelectorAll( '.toggled .menu-toggle' );

    for ( var toggle = 0; toggle < openedMenus.length; toggle++ ) {
        openedMenus[ toggle ].addEventListener( 'click', function() {
            openedMenus[ toggle ].click();
        } );
    }
} );

thanks Tom - I added this however it doesn't appear to do anything

Have updated the code, still doesn't seem to do anything

Sorry about that - made one more edit. Hopefully this is the one :)

just updated and cleared caches, still doesn't seem to be doing anything

Can you deactivate your caching/minifying so I can view the source of your site cleanly?

thanks - have deactivated.

Hi there,

If I may suggest:

You can try this script:

<script>
document.addEventListener( 'scroll', function( e ) {
    const openedMenus = document.querySelector( '#mobile-header' );
	const btn = openedMenus.querySelector( 'button.menu-toggle' );
    if(openedMenus.classList.contains('toggled')){
        btn.click();
    } 
} );
</script>

Thanks Elvin - that appears to work, appreciated.

No problem. :D

This archived topic is closed to new replies.