Projects
Modal Component
Build a fully accessible modal dialog with animations, focus trapping, scroll lock, keyboard navigation, and a promise-based API. Modals are one of the most nuanced UI components to implement correctly.
What You Will Build
1
Overlay & Animation
CSS transitions, scale+fade entry, scroll lock on open
2
Focus Trap
Keep Tab/Shift+Tab inside modal, restore focus on close
3
Accessibility
role=dialog, aria-modal, aria-labelledby, Escape to close
4
Promise API
await confirmDialog('Delete?') returns boolean
Accessibility Checklist
role="dialog" or "alertdialog"
Announces to screen readers what type of modal it is
aria-modal="true"
Tells screen readers to ignore content behind the modal
aria-labelledby
Links modal to its heading for a descriptive announcement
Focus moved to modal on open
Screen reader users should land inside the modal immediately
Focus trapped inside
Tab should cycle through modal elements only
Escape closes modal
Standard keyboard shortcut all users expect
Focus restored on close
Return focus to the trigger button after close
Scroll lock on open
Prevent background from scrolling while modal is open
Common Pitfalls
No focus trap — Tab key exits the modal, confusing keyboard and screen reader users
Intercept Tab events, cycle focus through only the modal's focusable elements.
Forgetting to restore focus — user loses their place in the page after modal closes
Store document.activeElement before opening. Call previousFocus.focus() on close.
Not preventing background scroll — page jumps when modal opens with scrollbar
document.body.style.overflow = 'hidden' on open. Restore on close. Or use overscroll-behavior.
display:none toggle — no animation possible, jarring UX
Use opacity + visibility + CSS transitions. visibility:hidden still allows transitions unlike display:none.
Build It Live
Code Editor
<button id="open">Open dialog</button>
<dialog id="dlg" aria-labelledby="dlg-title">
<h2 id="dlg-title">Delete file?</h2>
<p>This can't be undone.</p>
<form method="dialog">
<button value="cancel">Cancel</button>
<button value="delete" class="danger">Delete</button>
</form>
</dialog>
<p id="result"></p>Preview
Modal Component — step by step
1
Triggering and Trapping Focus
When a modal opens, move focus to the first interactive element inside it. Trap focus within the modal so Tab cycles only through its controls. This is critical for keyboard and screen-reader accessibility.
1 of 4
💡Prefer the Native dialog Element
The browser's built-in dialog element comes with focus trapping, Escape key handling, and proper ARIA roles out of the box. It also has a ::backdrop pseudo-element for styling the overlay. Building all this from a div requires significantly more code and is easier to get wrong.
🎯 Quick Check
Why should you lock body scrolling when a modal is open?
Next project