As a rule of thumb, don't use positive tab indexes. At all. If you want to be able to tab to something, just give the tabindex a value of zero, and use the markup order to dictate the sequence.
Negative tabindexes should only be used if you need to focus a non-interactive element. (Hyperlinks are interactive, so that's out).
Generally speaking, if you are navigating between hyperlinks, you should not mess with tabindex at all. Hyperlinks are already keyboard-focusable. Please don't put tabindex attributes on <a>
, <button>
, or <input>
elements. They are already part of the tab sequence.
If you have good reason to jump about in the sequence, there is an aria-flowto
attribute which is intended for this purpose, but it is poorly supported, and incompletely specified. You might want to try it out, though. If sub nav link 1 has the id subnavlink1
you would mark up link 1 like this:
<a href="whatever.html" aria-flowto="subnavlink1">Link 1</a>
This might work on some browsers, but I notice it doesn't work on Chrome, even though the Accessibility Tab in developer tools recognises its presence.
For more reliable deviation from the markup order tab sequence, listen for the focusout
or blur
event, on the element you are 'leaving' and use that event handler to focus on some other element. These events are very similar, both allowing you to redirect the tab sequence. They fire before the next element gets focus, so you can focus where you like. You may need to preventDefault or return false
Basic pattern might be something like this:
var lnk = document.querySelector("nav > a:nth-child(1)");
var snl = document.querySelector("#subnav > a:nth-child(1)");
lnk.addEventListener("focusout", function () {
snl.focus();
});
You should (of course) soft-code the nav indexes in the selector string, so that you can use the same trick on all the links if necessary.