Explain Codes LogoExplain Codes Logo

Prevent tabstop on A element (anchor link) in HTML

html
accessibility
css
javascript
Nikita BarsukovbyNikita BarsukovยทOct 3, 2024
โšกTLDR

To omit an anchor from tab navigation, add tabindex="-1" to the <a> tag:

<a href="#" tabindex="-1">Tab skips me ๐Ÿ˜ข</a>

This ditches focus, making sure the tab key hops over this link.

With CSS, you can fashion your link to look the part, while not being tabbable:

.linkButNotTabbable { cursor: pointer; text-decoration: underline; color: blue; }
<a class="linkButNotTabbable" tabindex="-1">I look clickable, but tabs ignore me ๐Ÿ˜Ž</a>

Tabstop prevention with CSS and better accessibility

Using CSS for no-tabstop strategy

An alternative to tabindex is to remove the href to prevent focus:

<span role="link" onclick="location.href='#'">Do I trick you into thinking I'm a link? ๐Ÿƒ</span>

This technique uses a span with role="link", masquerading as a link for accessibility tools while maintaining semantics. The onclick handler ensures it remains clickable.

Certain circumstances warrant non-focusable links:

  1. Navigation aids: Mouse users won't need these in tab order.
  2. Duplicate links: Makes sense if multiple navigation paths lead to the same destination.
  3. App UI controls: These fall more into the buttons category than traditional hyperlinks.

Keeping accessibility in mind

While playing around with the tab order, always remember:

  • Non-tabbable content, if not handled correctly, makes it inaccessible to screen readers.
  • If a resource is linked, ensure there's an alternate way to access it for keyboard navigation.

Following W3C's guidelines about using ARIA roles and tabindex appropriately can lead to better accessibility.

Ensuring a solid user experience

Handling focus invisibility

If you're looking for control, consider:

.nowYouSeeMeNowYouDont:focus { outline: none; /* Now I'm stealthy like a ninja ๐Ÿฅท */ }

But this may hamper usability for keyboard users. It's vital to strike a balance between visibility and looks.

Tabindex-Scripting interplay

JavaScript allows dynamic modification of tabindex, paving the way for advanced interaction designs:

document.querySelectorAll('.tabstopOptional').forEach(el => { el.setAttribute('tabindex', '-1'); /* Banished from tab kingdom! ๐Ÿ‘‘ */ });

Use scripting with caution and consider impact on differently-abled users.

Sticking to standards

When in doubt, look up the W3C rules. Regularly referring to trustworthy sources ensures that your solutions remain current and compliant.