0

This is the JS code responsible for the main navigation menu in the Twenty Fifteen theme:

function initMainNavigation( container ) {
    // Add dropdown toggle that display child menu items.
    container.find( '.menu-item-has-children > a' ).after( '<button class="dropdown-toggle" aria-expanded="false">' + screenReaderText.expand + '</button>' );

    // Toggle buttons and submenu items with active children menu items.
    container.find( '.current-menu-ancestor > button' ).addClass( 'toggle-on' );
    container.find( '.current-menu-ancestor > .sub-menu' ).addClass( 'toggled-on' );

    container.find( '.dropdown-toggle' ).click( function( e ) {
        var _this = $( this );
        e.preventDefault();
        _this.toggleClass( 'toggle-on' );
        _this.next( '.children, .sub-menu' ).toggleClass( 'toggled-on' );
        _this.attr( 'aria-expanded', _this.attr( 'aria-expanded' ) === 'false' ? 'true' : 'false' );
        _this.html( _this.html() === screenReaderText.expand ? screenReaderText.collapse : screenReaderText.expand );
    } );
}
initMainNavigation( $( '.main-navigation' ) );

The default behavior is to leave all opened submenus when another one is clicked. I'd like to modify this code so all opened submenus are closed when another one is clicked. Is this possible?

Any help would be appreciated.

Thanks in advance

1

In case anyone is interested, I think I managed to find a solution. Just had to add the following two lines of code just after the e.preventDefault(); line and before the _this.toggleClass( 'toggle-on' ); one:

container.find( '.dropdown-toggle.toggle-on' ).not( _this ).not( _this.parents( '.children, .sub-menu' ).prev( '.dropdown-toggle' ) ).removeClass( 'toggle-on' ).attr( 'aria-expanded', false );
container.find( '.children.toggled-on, .sub-menu.toggled-on' ).not( _this.next( '.children, .sub-menu' ) ).not( _this.parents( '.children, .sub-menu' ) ).removeClass( 'toggled-on' );

I don't know if there's a better way to do it, but this seems to work as I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.