Course contentsShow
← Web Development
Lesson 1151 of 2,98221. Accessible ComponentsFree lesson

Focus Trapping in Modals

Implementing focus management to keep keyboard navigation within an open modal dialog.

Focus Trapping in Modals

What you'll learn: How to keep keyboard users safely inside an open modal dialog so they don't accidentally interact with the page behind it.

The Core Idea

When you open a modal dialog, keyboard focus should stay trapped inside the modal until the user closes it. Without focus trapping, pressing Tab could move focus to elements hidden behind the overlay—creating a confusing and inaccessible experience.

Think of a modal like a locked room: once you enter, you can move around freely inside, but you can't walk through the walls to the hallway behind you. Similarly, Tab and Shift+Tab should cycle through only the focusable elements within the modal.

How Focus Trapping Works

When using showModal() (as opposed to show()), the <dialog> element provides native focus trapping. The browser automatically:

  1. Prevents Tab from reaching elements outside the dialog
  2. Cycles focus between the first and last focusable element inside
  3. Keeps focus contained until the modal closes

This is one of the major advantages of showModal() over show()—you get proper keyboard containment built-in.

What Gets Trapped

Focus trapping applies to all interactive elements inside the modal: buttons, links, form inputs, and anything with tabindex="0". When the user reaches the last focusable element and presses Tab, focus wraps back to the first element.

The Escape key should still work to close the modal (native <dialog> elements handle this automatically with showModal()).

Key Takeaway: Focus trapping keeps keyboard navigation contained within a modal dialog, preventing users from accidentally interacting with the inert page content behind it—a critical accessibility feature that showModal() provides automatically.