Closing Modals: Keyboard and Click
What you'll learn: How to let users dismiss modals using the Escape key, backdrop clicks, and close buttons in an accessible way.
Why Multiple Close Methods Matter
A modal dialog should offer users several intuitive ways to exit. Think of it like a room with multiple doors—some users naturally look for an "X" button, others instinctively press Escape, and some expect to click outside the dialog to dismiss it. Supporting all three methods ensures everyone can exit comfortably.
The Three Close Methods
1. Escape Key
Listen for the Escape key using a keydown event handler. When detected, close the modal and restore focus to the element that opened it (focus restoration pattern). This is expected behavior users rely on, especially keyboard-only users.
2. Backdrop Click
The backdrop is the semi-transparent overlay behind the modal. Clicking it should close the modal, but be careful: only trigger this when clicking the backdrop itself, not when clicks bubble up from inside the modal content. Check if event.target matches the backdrop element specifically.
3. Close Button
Always provide a visible close button (often styled as an "X" icon). Remember to include visually hidden text like "Close dialog" for screen reader users so they understand the button's purpose. This button should be keyboard-accessible and have proper focus styling.
Implementation Notes
All three methods should execute the same closing logic: close the modal, remove any focus trap, and return focus to the trigger element. The <dialog> element's .close() method handles much of this automatically when using showModal().
Key Takeaway: Accessible modals must support Escape key, backdrop clicks, and an explicit close button—giving all users predictable, comfortable ways to dismiss the dialog regardless of their interaction method.