primary-navigation.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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,
  37. elements,
  38. selectors,
  39. lastEl,
  40. firstEl,
  41. activeEl,
  42. tabKey,
  43. shiftKey,
  44. escKey;
  45. modal = document.querySelector( '.' + id + '-navigation' );
  46. selectors = 'input, a, button';
  47. elements = modal.querySelectorAll( selectors );
  48. elements = Array.prototype.slice.call( elements );
  49. elements = elements.filter( function ( el ) {
  50. return ! el.classList.contains( 'woocommerce-cart-link' ); // ignore this element because it's hidden on mobile
  51. } );
  52. tabKey = event.keyCode === 9;
  53. shiftKey = event.shiftKey;
  54. escKey = event.keyCode === 27;
  55. activeEl = document.activeElement;
  56. lastEl = elements[ elements.length - 1 ];
  57. firstEl = elements[ 0 ];
  58. if ( escKey ) {
  59. event.preventDefault();
  60. wrapper.classList.remove(
  61. id + '-navigation-open',
  62. 'lock-scrolling'
  63. );
  64. openButton.focus();
  65. }
  66. if ( ! shiftKey && tabKey && lastEl === activeEl ) {
  67. event.preventDefault();
  68. firstEl.focus();
  69. }
  70. if ( shiftKey && tabKey && firstEl === activeEl ) {
  71. event.preventDefault();
  72. lastEl.focus();
  73. }
  74. // If there are no elements in the menu, don't move the focus
  75. if ( tabKey && firstEl === lastEl ) {
  76. event.preventDefault();
  77. }
  78. } );
  79. };
  80. window.addEventListener( 'load', function () {
  81. new navMenu( 'primary' );
  82. new navMenu( 'woo' );
  83. } );
  84. } )();