Overlays and disclosure widgets · mid
Modal dialog with a focus trap
A modal dialog renders above everything, labels itself, moves focus inside when it opens, keeps Tab inside, closes on Escape (only the top one), makes the background inert and unscrollable, and returns focus to the button that opened it; native <dialog> with showModal() gives most of this for free.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Native: <dialog> + showModal() puts it in the top layer, makes the rest of the page inert, closes on Escape (only the last opened), styles ::backdrop, and focuses the first focusable element (or the autofocus one). It is Baseline widely available since March 2022. closedby='any' adds light dismiss (outside click) — check support before relying on it.
- Custom: render in a portal; role='dialog', aria-modal='true', aria-labelledby → the title id (aria-describedby optional).
- Focus: on open, focus the first sensible element (or the least destructive button for confirm dialogs); Tab and Shift+Tab wrap inside; on close, return focus to the opener (APG).
- Background: inert attribute on the app root (or aria-hidden plus a trap); lock body scroll and compensate for the scrollbar width (or scrollbar-gutter: stable) to avoid layout shift.
- Escape closes only the topmost modal: keep a stack of open layers.
- Backdrop click closes only if the press started on the backdrop (dragging a text selection out of the dialog must not close it).
- API: open/onClose (controlled), title, children, footer actions; a promise-based confirm (await confirm('Delete?')) is a nice extra.
The red pen
Common traps: mistake → fix
Mistake: Render inside a parent with overflow: hidden or a z-index stack
Fix: clipped or hidden; use a portal or the top layer.
Mistake: Forget to restore focus
Fix: keyboard users land at the top of the page.
Mistake: Close on mouseup over the backdrop
Fix: drags that end outside close the dialog.
Mistake: aria-modal='true' without making the background inert
Fix: screen readers can still wander outside.
Easy to hard
Questions interviewers ask, easy to hard
- Build a reusable modal.
- What happens to focus when it opens and closes?
- Two modals are open and the user presses Escape.
- Native <dialog> or a custom one? Why?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.