# Return Focus After Closing Popups

> Remembers which element opened a popup or modal dialog and moves keyboard focus back to it when the dialog closes, a common gap in theme and plugin popups.

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

## Code

```html
<script>
(function () {
    var opener = null;
    document.addEventListener('click', function (event) {
        var el = event.target.closest('a, button, [tabindex]');
        if (el && !el.closest('dialog, [role="dialog"], [aria-modal="true"]')) { opener = el; }
    }, true);
    function visible(d) {
        return d.isConnected && d.getAttribute('aria-hidden') !== 'true' && !d.hidden && (d.tagName !== 'DIALOG' || d.open) && d.getClientRects().length > 0;
    }
    var open = [];
    var pending = false;
    function check() {
        pending = false;
        var now = Array.prototype.filter.call(document.querySelectorAll('dialog, [role="dialog"], [aria-modal="true"]'), visible);
        var closed = open.filter(function (d) { return now.indexOf(d) === -1; });
        if (closed.length && opener && document.contains(opener)) {
            var active = document.activeElement;
            if (!active || active === document.body || !document.contains(active) || closed.some(function (d) { return d.contains(active); })) { opener.focus(); }
        }
        open = now;
    }
    new MutationObserver(function () {
        if (!pending) { pending = true; requestAnimationFrame(check); }
    }).observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ['open', 'hidden', 'aria-hidden', 'class', 'style'] });
})();
</script>
```

## Notes

Works with dialogs that use the dialog element or role="dialog" and are hidden by removing them, hiding them or toggling aria-hidden.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Return Focus After Closing Popups" 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/
