# 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.

- Type: HTML
- Runs: Site-wide footer
- Category: [Accessibility](https://wpide.com/library/category/accessibility/)
- Tags: menus, keyboard, escape
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/a11y-escape-closes-menus/

## Code

```html
<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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Close Open Menus With the Escape Key" in its snippet library and add it in one click; or create a new HTML snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
