
Declarative Focus Trapping and Background Locking with the HTML inert Attribute
When a modal dialog or navigation drawer opens, the rest of the application body must be deactivated: background elements must not receive clicks, must not be focusable via the Tab key, and must not be announced by screen readers.
Historically, this required complex "focus trap" JavaScript libraries that listened for keydown events to wrap focus and looped through every background link to inject tabindex="-1" and aria-hidden="true".
The HTML inert boolean attribute performs all of these actions declaratively in a single attribute.
Example
<main id="app-content" inert>
<!-- Entire page is now non-interactive and hidden from accessibility tree -->
</main>
<dialog open id="active-modal">
<h2>Account Verified</h2>
<button type="button">Continue</button>
</dialog>
Implementation
function openModal(modalEl) {
modalEl.showModal();
document.getElementById('app-content').setAttribute('inert', '');
}
function closeModal(modalEl) {
modalEl.close();
document.getElementById('app-content').removeAttribute('inert');
}
Main Point: The inert attribute replaces dozens of lines of fragile focus-trapping JavaScript by declaratively removing background DOM subtrees from focus, interaction, and accessibility trees.
Credits
Photo by Dan Freeman on Unsplash