themes-wordpress/seedlet/assets/js/primary-navigation.js
Jeff Ong 41f1d0697c
Seedlet: fix keyboard navigation (#2305)
* Scope focus styles to the site.

* Implement keyboard navigation trapping in menu modal.

* Change taborder of menu buttons.

* Cleanup focus selector.

* Fix keyboard nav within modal.

* Refactor primary menu logic to enable correct tab order.

* Refactor to work with multiple navs.

* Fix empty cart bug.
2020-08-12 12:30:02 -04:00

79 lines
No EOL
2.1 KiB
JavaScript

/**
* File primary-navigation.js.
*
* Required to open and close the mobile navigation.
*/
( function() {
/**
* Menu Toggle Behaviors
*
* @param {Element} element
*/
var navMenu = function ( id ){
var wrapper = document.body; // this is the element to which a CSS class is added when a mobile nav menu is open
var openButton = document.getElementById( `${ id }-open-menu` );
var closeButton = document.getElementById( `${ id }-close-menu` );
openButton.onclick = function() {
wrapper.classList.add( `${ id }-navigation-open` );
wrapper.classList.add( 'lock-scrolling' );
closeButton.focus();
}
closeButton.onclick = function() {
wrapper.classList.remove( `${ id }-navigation-open` );
wrapper.classList.remove( 'lock-scrolling' );
openButton.focus();
}
/**
* Trap keyboard navigation in the menu modal.
* Adapted from TwentyTwenty
*/
document.addEventListener( 'keydown', function( event ) {
if ( ! wrapper.classList.contains( `${ id }-navigation-open` ) ){
return;
}
var modal, elements, selectors, lastEl, firstEl, activeEl, tabKey, shiftKey, escKey;
modal = document.querySelector( `.${ id }-navigation` );
selectors = 'input, a, button';
elements = modal.querySelectorAll( selectors );
elements = Array.prototype.slice.call( elements );
tabKey = event.keyCode === 9;
shiftKey = event.shiftKey;
escKey = event.keyCode === 27;
activeEl = document.activeElement;
lastEl = elements[ elements.length - 1 ];
firstEl = elements[0];
if ( escKey ) {
event.preventDefault();
wrapper.classList.remove( `${ id }-navigation-open`, 'lock-scrolling' );
openButton.focus();
}
if ( ! shiftKey && tabKey && lastEl === activeEl ) {
event.preventDefault();
firstEl.focus();
}
if ( shiftKey && tabKey && firstEl === activeEl ) {
event.preventDefault();
lastEl.focus();
}
// If there are no elements in the menu, don't move the focus
if ( tabKey && firstEl === lastEl ) {
event.preventDefault();
}
});
}
window.addEventListener( 'load', function() {
new navMenu( 'primary' );
new navMenu( 'woo' );
});
} )();