primary-navigation.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. tabKey = event.keyCode === 9;
  42. shiftKey = event.shiftKey;
  43. escKey = event.keyCode === 27;
  44. activeEl = document.activeElement;
  45. lastEl = elements[ elements.length - 1 ];
  46. firstEl = elements[0];
  47. if ( escKey ) {
  48. event.preventDefault();
  49. wrapper.classList.remove( `${ id }-navigation-open`, 'lock-scrolling' );
  50. openButton.focus();
  51. }
  52. if ( ! shiftKey && tabKey && lastEl === activeEl ) {
  53. event.preventDefault();
  54. firstEl.focus();
  55. }
  56. if ( shiftKey && tabKey && firstEl === activeEl ) {
  57. event.preventDefault();
  58. lastEl.focus();
  59. }
  60. // If there are no elements in the menu, don't move the focus
  61. if ( tabKey && firstEl === lastEl ) {
  62. event.preventDefault();
  63. }
  64. });
  65. }
  66. window.addEventListener( 'load', function() {
  67. new navMenu( 'primary' );
  68. new navMenu( 'woo' );
  69. });
  70. } )();