primary-navigation.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. openButton.onclick = function() {
  17. wrapper.classList.add( `${ id }-navigation-open` );
  18. wrapper.classList.add( 'lock-scrolling' );
  19. closeButton.focus();
  20. }
  21. closeButton.onclick = function() {
  22. wrapper.classList.remove( `${ id }-navigation-open` );
  23. wrapper.classList.remove( 'lock-scrolling' );
  24. openButton.focus();
  25. }
  26. /**
  27. * Trap keyboard navigation in the menu modal.
  28. * Adapted from TwentyTwenty
  29. */
  30. document.addEventListener( 'keydown', function( event ) {
  31. if ( ! wrapper.classList.contains( `${ id }-navigation-open` ) ){
  32. return;
  33. }
  34. var modal, elements, selectors, lastEl, firstEl, activeEl, tabKey, shiftKey, escKey;
  35. modal = document.querySelector( `.${ id }-navigation` );
  36. selectors = 'input, a, button';
  37. elements = modal.querySelectorAll( selectors );
  38. elements = Array.prototype.slice.call( elements );
  39. tabKey = event.keyCode === 9;
  40. shiftKey = event.shiftKey;
  41. escKey = event.keyCode === 27;
  42. activeEl = document.activeElement;
  43. lastEl = elements[ elements.length - 1 ];
  44. firstEl = elements[0];
  45. if ( escKey ) {
  46. event.preventDefault();
  47. wrapper.classList.remove( `${ id }-navigation-open`, 'lock-scrolling' );
  48. openButton.focus();
  49. }
  50. if ( ! shiftKey && tabKey && lastEl === activeEl ) {
  51. event.preventDefault();
  52. firstEl.focus();
  53. }
  54. if ( shiftKey && tabKey && firstEl === activeEl ) {
  55. event.preventDefault();
  56. lastEl.focus();
  57. }
  58. // If there are no elements in the menu, don't move the focus
  59. if ( tabKey && firstEl === lastEl ) {
  60. event.preventDefault();
  61. }
  62. });
  63. }
  64. window.addEventListener( 'load', function() {
  65. new navMenu( 'primary' );
  66. new navMenu( 'woo' );
  67. });
  68. } )();