Skip to content

Commit

Permalink
fix: close the nav when it loses focus, e.g keyboard user tabs out of it
Browse files Browse the repository at this point in the history
  • Loading branch information
shsteimer committed Jun 13, 2024
1 parent 72b31eb commit dfe221a
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 @@ -78,11 +93,15 @@ function toggleMenu(nav, navSections, forceExpanded = null) {
});
}
// 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 dfe221a

Please sign in to comment.