Roving tabindex for keyboard navigation around JavaScript widgets
Setting the
tabindex
of the focused element to “0” ensures that if the user tabs away from the widget and then returns, the selected item within the group retains focus. Note that updating thetabindex
to “0” requires also updating the previously selected item totabindex="-1"
. This technique involves programmatically moving focus in response to key events and updating thetabindex
to reflect the currently focused item. To do this:Bind a key down handler to each element in the group, and when an arrow key is used to move to another element:
- programmatically apply focus to the new element,
- update the
tabindex
of the focused element to “0”, and- update the
tabindex
of the previously focused element to “-1”.Here’s an example of a WAI-ARIA tree view using this technique.
For a more visual explanation, see the following video by Rob Dodson: