Urgent.News

What's breaking now, across thousands of outlets.

Tech

Web Accessibility: Keyboard Traps in Modals

Accessibility: Keyboard Traps in Modals Every developer should care about accessibility. Plenty of people can only use a keyboard to browse the web, like blind users and people with physical disabilities. Modals, calendars, dropdowns, any custom widget you build, they all need to work without a mouse. This article looks at one specific problem, keyboard traps. That's when a user moves focus into…

Accessibility is crucial for web development, especially for users who rely on keyboards to navigate the web. Modals, calendars, and dropdowns are examples of custom widgets that must function without a mouse. One common issue is keyboard traps, where a user becomes unable to move focus back out of a part of the page using only a keyboard.

Keyboard traps typically occur due to custom JavaScript that interferes with the browser's normal focus behavior. However, modals should trap focus intentionally to prevent the rest of the page from being accessible while the modal is open. Users should only be able to navigate between elements within the modal using the Tab key, and the focus should return to the element that opened the modal once it is closed. A way to close the modal via keyboard is essential, such as the Escape key, a Cancel button, or a Close button.

The native `<dialog>` element in HTML already handles the trapping of focus and proper closing behavior. In a React application, the `<dialog>` element can be used to create a modal without needing to write any keyboard code. By calling the `.showModal()` method on the dialog, the browser automatically manages focus trapping, closing the modal with the Escape key, and returning focus to the element that opened the modal after it closes. This adheres to WCAG Success Criterion 2.1.2, which states that there should be no keyboard traps.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

I collected product forms worth borrowing

I wanted a place where you could type “feedback,” find a thoughtful form, and start using it. Not like a generic template, but studied questions in the right order and follow-ups that we know work.

More from Monday 14 September →