Other keyboard focus considerations

Understand how to manage keyboard focus for in-page links, single-page applications (SPAs) and scrollable containers — and when it’s expected to trap keyboard focus within a widget.

On this page

In the past, when a non-interactive element like a <div> or <h1> was the target of an in-page or anchor link, it needed to have tabindex="-1". This was to ensure that keyboard focus actually moved to that target and did not stay on the link itself.

This was caused by browser and screen reader bugs that have now been fixed everywhere but in Internet Explorer 11. Therefore, tabindex="-1" on the non-interactive target of an in-page link is not necessary, unless supporting Internet Explorer 11 or below is required.

However, remember that tabindex="-1" is still required on non-interactive elements to which focus is being moved programmatically via JavaScript.

If tabindex="1" is needed, add and remove it dynamically

If focus is being moved programmatically, and the target is a large block container such as the <main> element, then make sure to add and remove tabindex="-1" programmatically to avoid causing problems for keyboard users.

To learn why and how to add and remove tabindex="-1" dynamically in such a scenario, see Update 3 — A comment from gov.uk — Your skip links are broken — Axess Lab.

Focus in single-page applications (SPAs)

Single-page applications or SPAs present additional considerations for managing keyboard focus.

Normally, when navigating between web pages, there is a programmatic indication when a new page is loaded, and focus is expected to have been reset to the top of the document.

In a SPA, when a new ‘page’ or view is navigated (routed) to, there is no full-page refresh to indicate to the user that new content has been loaded. If the developer does not do anything to it, focus will either stay on the element that initiated the change, or worse, disappear entirely.

To address this, when a new view is loaded in an SPA, focus should move to a meaningful location that will helpfully orient the user, such as to the heading element at the top of the updated content.

For more on managing focus in SPAs, see:

Make scrollable containers focusable

Sometimes content is bigger than the box or container that it’s visually displayed in. In such cases, the developer can use the CSS overflow property to give the container the vertical or horizontal scrollbars it needs to let users scroll around to see all the content in the container.

To ensure that these scrollable containers are keyboard accessible, a few things need to happen, including adding tabindex="0" to the container.

For help, see:

Trapping focus

With some interactive widgets, notably modal dialogs, keyboard focus is expected to be constrained or ‘trapped’ within the widget in order to keep the user focussed on the task at hand.

For more on trapping focus, see Using JavaScript to trap focus in an element — Hidde de Vries.