Skip to content

Commit d9bb484

Browse files
authored
Global Header/Navigation: Switch to observer for menu open & close actions (#682)
1 parent 8ba8c8a commit d9bb484

File tree

1 file changed

+23
-9
lines changed
  • mu-plugins/blocks/global-header-footer/js

1 file changed

+23
-9
lines changed

mu-plugins/blocks/global-header-footer/js/view.js

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* global MutationObserver */
12
/**
23
* File wporg-global-header-script.js.
34
*
@@ -195,7 +196,7 @@
195196

196197
const openButtons = document.querySelectorAll(
197198
'.global-header__navigation [data-wp-on-async--click="actions.openMenuOnClick"],' +
198-
'.global-header__search [data-wp-on-async--click="actions.openMenuOnClick"]'
199+
'.global-header__search [data-wp-on-async--click="actions.openMenuOnClick"]'
199200
);
200201
openButtons.forEach( function ( button ) {
201202
// When any open menu button is clicked, find any existing close buttons and click them.
@@ -215,16 +216,29 @@
215216
} );
216217
} );
217218

218-
const closeButtons = document.querySelectorAll(
219-
'.global-header__navigation [data-wp-on-async--click="actions.closeMenuOnClick"],' +
220-
'.global-header__search [data-wp-on-async--click="actions.closeMenuOnClick"]'
221-
);
222-
// When the global menus are closed (close button is clicked), remove the helper class.
223-
closeButtons.forEach( function ( button ) {
224-
button.addEventListener( 'click', function () {
225-
document.documentElement.classList.remove( 'has-global-modal-open' );
219+
// Watching for changes to the html element's class, which indicates open/close state of navigation.
220+
const observer = new MutationObserver( ( mutations ) => {
221+
mutations.forEach( ( mutation ) => {
222+
const oldClass = mutation.oldValue || '';
223+
const newClass = mutation.target.className || '';
224+
if ( oldClass.includes( 'has-modal-open' ) && ! newClass.includes( 'has-modal-open' ) ) {
225+
// Menu has closed, remove the helper class if it exists. If the previously
226+
// open menu was not the global nav, there will be not effect here.
227+
mutation.target.classList.remove( 'has-global-modal-open' );
228+
} else if ( ! oldClass.includes( 'has-modal-open' ) && newClass.includes( 'has-modal-open' ) ) {
229+
// Any nav menu has opened, scroll to the top of the page to show the
230+
// entire menu (and prevent incorrect positioning).
231+
window.scrollTo( { top: 0, behavior: 'instant' } );
232+
}
226233
} );
227234
} );
235+
236+
// Observe the html element for changes only to the class attribute.
237+
observer.observe( document.documentElement, {
238+
attributes: true,
239+
attributeFilter: [ 'class' ],
240+
attributeOldValue: true,
241+
} );
228242
} );
229243

230244
window.addEventListener( 'resize', () => {

0 commit comments

Comments
 (0)