Close Open Menus With the Escape Key
Lets keyboard users press Escape to close an open dropdown or mobile menu and returns focus to the button or link that opened it.
Opens WPIDE on
Code
<script>
document.addEventListener('keydown', function (event) {
if (event.key !== 'Escape') { return; }
var open = document.querySelectorAll('[aria-expanded="true"]');
if (!open.length) { return; }
var last = open[open.length - 1];
last.click();
if (last.getAttribute('aria-expanded') === 'true') {
last.setAttribute('aria-expanded', 'false');
var item = last.closest('.is-open, .focus, .toggled-on');
if (item) { item.classList.remove('is-open', 'focus', 'toggled-on'); }
}
last.focus();
});
</script>
Notes
Works with menus that mark the open state with aria-expanded="true" on the toggle, which most modern themes and the Navigation block do.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.