Skip to content

Commit

Permalink
Merge pull request #369 from shsteimer/header-nav-a11y-fix
Browse files Browse the repository at this point in the history
fix: close the nav when it loses focus, e.g keyboard user tabs out of it
  • Loading branch information
fkakatie authored Jul 30, 2024
2 parents 555e045 + 980829d commit 66f47c4
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions blocks/header/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,21 @@ function closeOnEscape(e) {
}
}

function closeOnFocusLost(e) {
const nav = e.currentTarget;
if (!nav.contains(e.relatedTarget)) {
const navSections = nav.querySelector('.nav-sections');
const navSectionExpanded = navSections.querySelector('[aria-expanded="true"]');
if (navSectionExpanded && isDesktop.matches) {
// eslint-disable-next-line no-use-before-define
toggleAllNavSections(navSections, false);
} else if (!isDesktop.matches) {
// eslint-disable-next-line no-use-before-define
toggleMenu(nav, navSections, false);
}
}
}

function openOnKeydown(e) {
const focused = document.activeElement;
const isNavDrop = focused.className === 'nav-drop';
Expand Down Expand Up @@ -77,12 +92,16 @@ function toggleMenu(nav, navSections, forceExpanded = null) {
drop.removeEventListener('focus', focusNavSection);
});
}

// enable menu collapse on escape keypress
if (!expanded || isDesktop.matches) {
// collapse menu on escape press
window.addEventListener('keydown', closeOnEscape);
// collapse menu on focus lost
nav.addEventListener('focusout', closeOnFocusLost);
} else {
window.removeEventListener('keydown', closeOnEscape);
nav.removeEventListener('focusout', closeOnFocusLost);
}
}

Expand Down

0 comments on commit 66f47c4

Please sign in to comment.