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.
Opens WPIDE on
Code
<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 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.