An updated theme (based on Atticus Finch) for ClassicPress
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.2 KiB

3 years ago
  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. // Set menu items with submenus to aria-haspopup="true".
  42. for ( var i = 0, len = subMenus.length; i < len; i++ ) {
  43. subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
  44. }
  45. // Each time a menu link is focused or blurred, toggle focus.
  46. for ( i = 0, len = links.length; i < len; i++ ) {
  47. links[i].addEventListener( 'focus', toggleFocus, true );
  48. links[i].addEventListener( 'blur', toggleFocus, true );
  49. }
  50. /**
  51. * Sets or removes .focus class on an element.
  52. */
  53. function toggleFocus() {
  54. var self = this;
  55. // Move up through the ancestors of the current link until we hit .nav-menu.
  56. while ( -1 === self.className.indexOf( 'nav-menu' ) ) {
  57. // On li elements toggle the class .focus.
  58. if ( 'li' === self.tagName.toLowerCase() ) {
  59. if ( -1 !== self.className.indexOf( 'focus' ) ) {
  60. self.className = self.className.replace( ' focus', '' );
  61. } else {
  62. self.className += ' focus';
  63. }
  64. }
  65. self = self.parentElement;
  66. }
  67. }
  68. } )();