Anchor links and tab focusing

127 views Asked by At

I’m having an issue with multiple anchor links and keyboard navigation with the tab button.

I have 4 links adjacent to one another and they all link to a different anchor link on the page. When I hit enter on the first link it takes me to the first anchor, as it should, however, when I press tab again the page returns back to the row of links where I click the first link and then the focus is shifted to the 2nd link in my row of 4 links. It’s very annoying to have the page keep bobbing up and down when I try to navigate via keyboard.

I would prefer for the behavior to be that when I press tab again after hitting enter the first time that focus is shifted to the nearest hyperlink on the my screen and not to the link adjacent to the first link I clicked back at the top of the page.

This page has anchors/hyperlinks in the way I’d like to have mine: https://www.sjsu.edu/president/from-the-president/100-days/index.php

Is this something I can achieve easily?

I tried adjusting where anchors were placed and some scripts but could not get the result I needed.

1

There are 1 answers

1
slugolicious On

So you have "in page" links. Links that take you further down the page rather than taking you to a new page.

What kind of HTML element is the destination of that link? If it's not an interactive element, such as a heading (<h2>), paragraph (<p>), or list (<ul>), then some browsers will only scroll the page to the destination element but won't actually move the (keyboard) focus there. So your focus is still on the link that you pressed enter on. So when you press tab again, the keyboard focus moves from your first link to the second link. Since the first enter visually scrolled the page, the next tab will scroll the page back up to the second link.

You can get around this by putting tabindex="-1" on the destination element.

<a href="#alpha">first</a>
<a href="#beta">second</a>
<a href="#gamma">third</a>
...
<h2 id="alpha" tabindex="-1">important stuff</h2>
...
<a href="http://example.com">some other link</a>

In the above example, pressing enter on the "first" link will scroll the page (if necessary) and move the focus to the <h2>. When I press tab, focus should move to the "some other link" rather than the "second" link.