primary-navigation.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * File primary-navigation.js.
  3. *
  4. * Required to open and close the mobile navigation.
  5. */
  6. ( function() {
  7. /**
  8. * Menu Toggle Behaviors
  9. *
  10. * @param {Element} element
  11. */
  12. var navMenu = function ( id ){
  13. var wrapper = document.body; // this is the element to which a CSS class is added when a mobile nav menu is open
  14. var openButton = document.getElementById( id + '-open-menu' );
  15. var closeButton = document.getElementById( id + '-close-menu' );
  16. if ( openButton && closeButton ){
  17. openButton.onclick = function() {
  18. wrapper.classList.add( id + '-navigation-open' );
  19. wrapper.classList.add( 'lock-scrolling' );
  20. closeButton.focus();
  21. }
  22. closeButton.onclick = function() {
  23. wrapper.classList.remove( id + '-navigation-open' );
  24. wrapper.classList.remove( 'lock-scrolling' );
  25. openButton.focus();
  26. }
  27. }
  28. /**
  29. * Trap keyboard navigation in the menu modal.
  30. * Adapted from TwentyTwenty
  31. */
  32. document.addEventListener( 'keydown', function( event ) {
  33. if ( ! wrapper.classList.contains( id + '-navigation-open' ) ){
  34. return;
  35. }
  36. var modal, elements, selectors, lastEl, firstEl, activeEl, tabKey, shiftKey, escKey;
  37. modal = document.querySelector( '.${ id }-navigation' );
  38. selectors = "input, a, button";
  39. elements = modal.querySelectorAll( selectors );
  40. elements = Array.prototype.slice.call( elements );
  41. elements = elements.filter( function( el ) {
  42. return ! el.classList.contains( 'woocommerce-cart-link' ); // ignore this element because it's hidden on mobile
  43. });
  44. tabKey = event.keyCode === 9;
  45. shiftKey = event.shiftKey;
  46. escKey = event.keyCode === 27;
  47. activeEl = document.activeElement;
  48. lastEl = elements[ elements.length - 1 ];
  49. firstEl = elements[0];
  50. if ( escKey ) {
  51. event.preventDefault();
  52. wrapper.classList.remove( id + '-navigation-open', 'lock-scrolling' );
  53. openButton.focus();
  54. }
  55. if ( ! shiftKey && tabKey && lastEl === activeEl ) {
  56. event.preventDefault();
  57. firstEl.focus();
  58. }
  59. if ( shiftKey && tabKey && firstEl === activeEl ) {
  60. event.preventDefault();
  61. lastEl.focus();
  62. }
  63. // If there are no elements in the menu, don't move the focus
  64. if ( tabKey && firstEl === lastEl ) {
  65. event.preventDefault();
  66. }
  67. });
  68. }
  69. window.addEventListener( 'load', function() {
  70. new navMenu( 'primary' );
  71. new navMenu( 'woo' );
  72. });
  73. } )();