I've created a click menu in WordPress and so far so good, except clicking outside the menu to close it. The below code works, but there has got to be a better way.
Question: If you have any tips on improving this so that I don't have to call each menu class individually and can use a shared class, please let me know:
/*
* Close .sub-menu when clicked outside menu
*
*/
$( document ).bind( 'click touchend', 'html', function( e ) {
var a = e.target;
if ( $( a ).parents( '.nav-primary' ).length === 0 ) {
$( '.nav-primary li' ).removeClass( 'sub-menu-open' );
$( '.nav-primary li .sub-menu-toggle' ).attr( 'aria-expanded', 'false' ).attr( 'aria-pressed', 'false' );
$( '.nav-primary li' ).children( '.sub-menu-toggle' ).children( '.screen-reader-text' ).text( visionary_objectL10n.openChildMenu );
} // .nav-primary
if ( $( a ).parents( '.nav-tertiary' ).length === 0 ) {
$( '.nav-tertiary li' ).removeClass( 'sub-menu-open' );
$( '.nav-tertiary li .sub-menu-toggle' ).attr( 'aria-expanded', 'false' ).attr( 'aria-pressed', 'false' );
$( '.nav-tertiary li' ).children( '.sub-menu-toggle' ).children( '.screen-reader-text' ).text( visionary_objectL10n.openChildMenu );
} // nav-tertiary
if ( $( a ).parents( '.nav-procedures' ).length === 0 ) {
$( '.nav-procedures li' ).removeClass( 'sub-menu-open' );
$( '.nav-procedures li .sub-menu-toggle' ).attr( 'aria-expanded', 'false' ).attr( 'aria-pressed', 'false' );
$( '.nav-procedures li' ).children( '.sub-menu-toggle' ).children( '.screen-reader-text' ).text( visionary_objectL10n.openChildMenu );
} // nav-procedures
$( document ).unbind( 'click touchend', 'html' );
} );
What I've tried.
This doesn't work. When I click outside it works but when I click another menu the sub-menus I was just clicking on stays open. I am clearly just guessing, I have no clue.
$( document ).bind( 'click touchend', 'html', function(e) {
var target = e.target,
parents = $( target ).parents( 'nav' );
if ( $( parents ).length === 0 ) {
$( target ).parents().find( 'li' ).removeClass( 'sub-menu-open' );
}
$( document ).unbind( 'click touchend', 'html' );
} );