Managing focus in an accessible modal dialog
Keyboard focus management for modal dialogs.
move focus in on open, trap Tab within the dialog, close on Escape, and restore focus to the trigger on close.
leaving focus behind the modal in the background.
WHAT THIS TESTS The interviewer wants the complete keyboard focus lifecycle of a modal, because a visually correct overlay that lets keyboard focus wander behind it is unusable for keyboard and screen reader users.
A GOOD ANSWER COVERS Mark the container with role dialog and aria-modal true, and give it an accessible name via aria-labelledby pointing at the title. On open, move focus into the dialog: typically the first interactive element, or the dialog container itself if the first control is destructive. While open, trap focus so Tab from the last focusable element wraps to the first and Shift+Tab from the first wraps to the last, and prevent the background from receiving focus, often by setting inert or aria-hidden on the rest of the page. Provide Escape to dismiss. On close, restore focus to the triggering element so the user returns to where they were. Record that trigger when opening.
COMMON WRONG ANSWERS Forgetting to restore focus dumps the user at the top of the document. Not trapping Tab lets focus slip to hidden background controls. Relying only on a CSS overlay without inert or aria-hidden leaves the background reachable by screen readers. Auto-focusing a destructive button risks accidental activation.
LIKELY FOLLOW-UPS How does the native dialog element and showModal simplify this, including the top layer and automatic backdrop? When is aria-hidden risky compared to inert? How do you handle nested dialogs? Where should focus go if the dialog has no focusable content?
ONE CONCRETE EXAMPLE A delete confirmation opens from a row menu. Focus moves to the Cancel button, not Delete, to avoid accidental destruction. Tab cycles only between Cancel and Delete; the page behind is inert. Escape and Cancel both close it, and focus returns to the row menu button, so a keyboard user continues seamlessly.
Read the original → w3.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.