In this episode, we're zeroing in on a crucial aspect of building modals: trapping focus for accessibility. First, we look at the problem—without focus trapping, pressing the Tab key just jumps around the entire page, not just the modal, which can be disorienting for keyboard users. Not good!
To fix this, we use Alpine's focus plugin to make sure that when a modal is open, keyboard navigation is trapped inside that modal. You'll see a demo of how to wrap your modal component with x-trap
, so users can Tab through fields and buttons inside it without escaping to the rest of the page.
Then, we take things a bit further by adding the .inert
modifier. This hides everything outside the modal from screen readers while it's open—super important for accessibility. We also try out .no-scroll
, which stops the background page from scrolling when the modal is active. If you've ever had a popup open and accidentally scrolled the whole page, you know how useful this is!
We wrap up by testing nested modals to make sure focus trapping still works as expected. All in all, you'll walk away knowing how to make your modals way more accessible and user-friendly.