Focus Management
When modals open, move focus inside them. When they close, return focus to the trigger. Trap focus within open modals to prevent screen readers from escaping.
When modals open, move focus inside them. When they close, return focus to the trigger. Trap focus within open modals to prevent screen readers from escaping.
function openModal(triggerEl) {
const modal = document.getElementById("modal");
modal.removeAttribute("hidden");
// Move focus to first focusable element
modal.querySelector("button, [href], input").focus();
// Store trigger for later
modal.dataset.trigger = triggerEl.id;
}
function closeModal() {
const modal = document.getElementById("modal");
modal.setAttribute("hidden", "");
// Return focus to the trigger
document.getElementById(modal.dataset.trigger).focus();
}
Losing focus context (no return focus on close) is one of the most common modal accessibility bugs.