|
| 1 | +/* global MutationObserver */ |
1 | 2 | /** |
2 | 3 | * File wporg-global-header-script.js. |
3 | 4 | * |
|
195 | 196 |
|
196 | 197 | const openButtons = document.querySelectorAll( |
197 | 198 | '.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"]' |
199 | 200 | ); |
200 | 201 | openButtons.forEach( function ( button ) { |
201 | 202 | // When any open menu button is clicked, find any existing close buttons and click them. |
|
215 | 216 | } ); |
216 | 217 | } ); |
217 | 218 |
|
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 | + } |
226 | 233 | } ); |
227 | 234 | } ); |
| 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 | + } ); |
228 | 242 | } ); |
229 | 243 |
|
230 | 244 | window.addEventListener( 'resize', () => { |
|
0 commit comments