From 74244afe84ae719d322600c51c161c522e08468e Mon Sep 17 00:00:00 2001 From: Kelly Dwan Date: Tue, 18 Jan 2022 11:52:01 -0500 Subject: [PATCH] Menu: Close other modals when when the "open" button is clicked (#97) * Attempt at closing other modals when when the "open" button is clicked This does not work because `MicroModal.close` overwrites the internal modal ID, so it looses track of what the current open modal is. * Switch to faking a click directly on the close buttons. --- .../js/wporg-global-header-script.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/mu-plugins/blocks/global-header-footer/js/wporg-global-header-script.js b/mu-plugins/blocks/global-header-footer/js/wporg-global-header-script.js index 4e1ec977d..74c10f981 100644 --- a/mu-plugins/blocks/global-header-footer/js/wporg-global-header-script.js +++ b/mu-plugins/blocks/global-header-footer/js/wporg-global-header-script.js @@ -168,7 +168,24 @@ ); }; + /* eslint-disable @wordpress/no-global-event-listener */ window.addEventListener( 'load', function () { new navMenu( '.global-header .global-header__navigation' ); + + const openButtons = document.querySelectorAll( '[data-micromodal-trigger]' ); + openButtons.forEach( function ( button ) { + // When any open menu button is clicked, find any existing close buttons and click them. + button.addEventListener( 'click', function ( event ) { + const thisModal = event.target.getAttribute( 'data-micromodal-trigger' ); + const closeButtons = Array.from( + document.querySelectorAll( 'button[data-micromodal-close]' ) + ).filter( + // Filter to find visible close buttons that are not for this modal. + ( _button ) => _button.offsetWidth > 0 && null === _button.closest( `#${ thisModal }` ) + ); + + closeButtons.forEach( ( _button ) => _button.click() ); + } ); + } ); } ); } )();