Concentrating the user’s focus on a tiny section of the page can be a challenging task, especially when such an endeavor deteriorates the experience. The “keyboard trap” is generally seen as a UI bug where “the keyboard focus is being locked on a component for no apparent reasons” (refer to W3C article on keyboard trap), this an undesirable situation.
The “keyboard trap” can be seen in a better light if we look at some of the accessibility issues it solves. For example, a screen overlay prevents mouse users from accessing everything beside the content placed on focus, but keyboard users still have full access to anything on the page. In order to emulate the overlay effect for keyboard users, we can use the “keyboard trap”. In the following lines, I’ll show you how. In the meantime, see the keyboard trap in action.
What works for mouse users, doesn’t necessarily works for other users:
Consider a modal window. Because of an overlay that stands between the page content and the modal, mouse users have no access to anything on the page but to what’s inside the modal, not keyboard users. Looking at a drawer panel or any off-screen component, we see the same problem occurring: any HTML component that might isolate part of the layout for mouse users doesn’t do the same for keyboard users.
But we need the experience to be as consistent as possible for all users. Therefore, the “keyboard trap” will accomplish for keyboard users what the overlay is already doing for mouse users, which is keeping users focused on the modal content by forcing the keyboard focus to loop only on all focusable elements of that modal.
The “keyboard trap” can be used to “prevent keyboard users from moving the focus inatvertantly outside of a component!”
The implementation logic of the keyboard trap:
Trapping the focus inside a component (modal window, drawer panel, …) can be simplified in the following steps:
- We get a reference to all focusable elements of the component (especially the first and the last)
- We use a “keydown listener” to track any key pressed especially the “tab”
- If “TAB” and “SHIFT” keys are pressed (tabbing backward)
- and the first focusable element is the one on focus, we move the focus to the last focusable element of the component (this creates a loop)
- If only “TAB” key is pressed (tabbing forward)
- and the last focusable element is the one on focus, we move the focus to the first focusable element of the component (this also creates a loop)
To preserve accessibility, it is imperative that we keep the same functionalities available to all users. In this case blocking access to anything but an off-screen content should be done not only to mouse users, but keyboard or other users as well. And we’ve just seen how the “keyboard trap” is a great solution for this. Do you have experience with keyboard traps? Please share your thoughts with us.