Local link targets must be focusable to prevent accessibility issues
- Published at
- Updated at
- Reading time
- 2min
You might think that when you bet on the web platform and rely on native HTML features, your website will be completely accessible. Unfortunately, this assumption is wrong in many cases.
If you want to learn about more inaccessible HTML features, a recent HTMHell article covered many of them. It's a great read!
This week, I've learned that even simple things, such as linking to local elements via id (<a href="#something">
), require careful consideration not to cause accessibility problems.
What's the issue with local links?
I've been reading How To Avoid Breaking Web Pages For Keyboard Users and learned that some assistive technologies rely on document
.
The activeElement
read-only property of the Document interface returns the Element within the DOM that currently has focus.
For example, when you're jumping through a page via your keyboard's TAB
key, document
will always reference the focused element. It can be links, buttons, inputs... you get the idea.
And that's great, but what happens when you follow a link pointing to an unfocusable element, like a skip link referencing the main
element or a "scroll to top" link returning you to a blog's headline?
Then, there's nothing to focus, and the document
moves to body
as a fallback. If assistive technology relies on document
, the context is lost. That's pretty poor UX. Ouch!
To resolve this issue, if you're targeting a container, headline or any other unfocusable element, make it focusable via tabindex="-1"
.
tabindex="-1"
defines that an element is focusable but not reachable via sequential keyboard navigation. Learn more about tabindex
on MDN.
And here's the fix in action.
document.activeElement
becomes after interacting with a local link.The fact that activeElement
can only be a focusable element is pretty reasonable. Still, it's puzzling that simple web features like linking to another HTML element must be evaluated and carefully considered to keep everything intact and accessible.
It's another case of "writing good and accessible HTML is tougher than the web industry thinks". But if you're reading this blog, you probably know this already. 😉
Join 5.5k readers and learn something new every week with Web Weekly.