navigation.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * navigation.js
  3. *
  4. * Handles toggling the navigation menu for small screens and enables tab
  5. * support for dropdown menus.
  6. */
  7. ( function() {
  8. var container, button, menu, links, subMenus;
  9. container = document.getElementById( 'site-navigation' );
  10. if ( ! container ) {
  11. return;
  12. }
  13. button = container.getElementsByTagName( 'button' )[0];
  14. if ( 'undefined' === typeof button ) {
  15. return;
  16. }
  17. menu = container.getElementsByTagName( 'ul' )[0];
  18. // Hide menu toggle button if menu is empty and return early.
  19. if ( 'undefined' === typeof menu ) {
  20. button.style.display = 'none';
  21. return;
  22. }
  23. menu.setAttribute( 'aria-expanded', 'false' );
  24. if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
  25. menu.className += ' nav-menu';
  26. }
  27. button.onclick = function() {
  28. if ( -1 !== container.className.indexOf( 'toggled' ) ) {
  29. container.className = container.className.replace( ' toggled', '' );
  30. button.setAttribute( 'aria-expanded', 'false' );
  31. menu.setAttribute( 'aria-expanded', 'false' );
  32. } else {
  33. container.className += ' toggled';
  34. button.setAttribute( 'aria-expanded', 'true' );
  35. menu.setAttribute( 'aria-expanded', 'true' );
  36. }
  37. };
  38. // Get all the link elements within the menu.
  39. links = menu.getElementsByTagName( 'a' );
  40. subMenus = menu.getElementsByTagName( 'ul' );
  41. // Each time a menu link is focused or blurred, toggle focus.
  42. for ( i = 0, len = links.length; i < len; i++ ) {
  43. links[i].addEventListener( 'focus', toggleFocus, true );
  44. links[i].addEventListener( 'blur', toggleFocus, true );
  45. }
  46. /**
  47. * Sets or removes .focus class on an element.
  48. */
  49. function toggleFocus() {
  50. var self = this;
  51. // Move up through the ancestors of the current link until we hit .nav-menu.
  52. while ( -1 === self.className.indexOf( 'nav-menu' ) ) {
  53. // On li elements toggle the class .focus.
  54. if ( 'li' === self.tagName.toLowerCase() ) {
  55. if ( -1 !== self.className.indexOf( 'focus' ) ) {
  56. self.className = self.className.replace( ' focus', '' );
  57. } else {
  58. self.className += ' focus';
  59. }
  60. }
  61. self = self.parentElement;
  62. }
  63. }
  64. } )();