What You'll Learn
You'll learn how to return keyboard focus to the element that opened a modal when the modal is dismissed, maintaining a smooth and logical navigation experience.
Why Focus Restoration Matters
When a user opens a modal dialog—typically by clicking or pressing Enter on a button—their keyboard focus moves into the modal. When they close it, focus shouldn't simply vanish into the void. Without proper restoration, keyboard users would lose their place on the page and have to Tab through everything again from the top.
Think of it like putting a bookmark in a book before opening an encyclopedia. When you close the encyclopedia, you want to return to exactly where you left off in your book, not back to page one.
How It Works
Before opening the modal, store a reference to the currently focused element (usually the button that triggered the modal):
const triggerButton = document.getElementById('open-modal');
const modal = document.getElementById('my-modal');
triggerButton.addEventListener('click', () => {
// Store the trigger element
const previouslyFocusedElement = document.activeElement;
modal.showModal();
// When modal closes, restore focus
modal.addEventListener('close', () => {
previouslyFocusedElement.focus();
}, { once: true });
});
The key is capturing document.activeElement before opening the modal, then calling .focus() on that stored element when the modal's close event fires.
The Navigation Context
This pattern maintains the user's "mental position" on the page. After dismissing a "Delete Account" modal, for example, focus returns to the "Delete Account" button they activated. They know exactly where they are and can continue navigating forward or backward from that point.
Key Takeaway: Always restore focus to the triggering element when a modal closes—it preserves navigation context and prevents keyboard users from losing their place on the page.