Would you like to use the tab key to navigate through each <li>
(search result) and use the up/down arrow keys to move around the list?
Cautiously consider using positive values for tabindex
. It's generally best to stick with the default browser focus order, which is based on DOM order. In this scenario, if you want users to tab through each <li>
in sequence, there's no need to assign a positive value to tabindex
, as the elements are already arranged in the desired tabbing order. Simply set them all to 0.
<ul className="search-result">
<li tabindex="0">title here...</li>
<li tabindex="0">title here...</li>
<li tabindex="0">title here...</li>
.
.
.
</ul>
In general, only interactive elements should have tabindex="0"
. Since an <li>
is not typically interactive, it could confuse users if they tabbed to it without being able to interact. Ask yourself: what can the user do once they reach the <li>
? If there's no interaction possible, it shouldn't be a tab stop.
Usually, <li>
elements contain interactive content like links or buttons, which are already tab stops by default and don't require a tabindex
.
Regarding navigation with the up/down arrow keys, these keys should ideally only move focus between interactive elements. I usually implement an onkeydown
event handler on the <ul>
element to manage arrow key functionality, adjusting tabindex as needed for each item in the list. However, this approach is suitable when the entire list functions as one tab stop and users must navigate between items using the arrow keys. If your requirements include both behaviors, further clarification may be necessary.
If the list is treated as one tab stop, all <li>
elements except the focused one will have tabindex="-1"
. The focused element will retain tabindex="0"
, enabling users to tab to the list as a whole and automatically focus on the previously selected item. This setup facilitates seamless up/down traversal of the list.
To handle up/down key presses, simply update the tabindex
attribute from 0 to -1 for the currently targeted list item, change the attribute from -1 to 0 for the next item, and utilize focus()
to switch focus to the newly selected element.