tab order and tab navigation simulation
This is a follow up of tab order and tabindex post, simulating tab order and tab navigation using left and right arrows.
In tab navigation, one uses
tabfor forward navigationshift + tabfor backward navigation
Let’s simulate tab navigation like so:
right arrowfor forward navigationleft arrowfor backward navigation
In order to simulate tab navigation we need to first simulate a tab order.
tab order simulation
Let’s simulate tab order like so:
- traverse the DOM in
preorder,depth-first traversalto find the all thefocusableelements.- use Document.querySelectorAll(), as it returns a list of the elements within the document (using depth-first pre-order traversal of the document’s nodes) that match the specified group of selectors.
- use
'input:not([type=hidden]), select, textarea, button, a[href], tabindex=0'as theselectorforquerySelectorAll - filter the returned
node listagainst the presence ofdisabledandtabindex=1attribute.
- a variable to keep track of the
current tabable index.
tab navigation simulation
Once the tab order is simulated, we can simulate simulate tab navigation like so:
- whenever right arrow is pressed, increment this index by 1 and focus the corresponding node.
- if the value of the index is more then the number of focusable element; reset it to 0.
- whenever left arrow is pressed, decrement this index by 1 and focus the corresponding node.
- if the value of the index is less then 0; reset it to the number of focusable element.
For the sake of simplicity, tabindex=X is not considered.
Whenever a focusable element is either added or removed from the DOM, we need to update the simulated tab order and corresponding current tabable index.
Refer CodePen example - tab navigation simulation to experience simulated tab navigation.
See the Pen tab navigation simulation by Sarbbottam Bandyopadhyay (@sarbbottam) on CodePen.
For convenience, I have also embedded the corresponding JavaScript below.
See the Pen tab navigation simulation by Sarbbottam Bandyopadhyay (@sarbbottam) on CodePen.
Do browsers facilitate
tab navigationin similar fashion?
I have no idea :)
If you have enjoyed reading this post you can follow me on twitter @sarbbottam and learn about any new posts. Opinions expressed are solely my own and do not express the views or opinions of my employer.