diff --git a/blocks/header/header.js b/blocks/header/header.js index f7f719d5c2..6719d340e1 100644 --- a/blocks/header/header.js +++ b/blocks/header/header.js @@ -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'; @@ -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); } }