Managing focus in a Single-Page Application (SPA)
The Single Page Application (SPA) architecture relies on a simple principle: the browser never reloads the page. All content is updated dynamically.
For accessibility, a page change must therefore be simulated so that focus is moved back to the top of the content and the page title is announced by screen readers.
To achieve this, you need to:
- Update the page
<title>on every view change. - Add an anchor tag at the very top of each page (as the first element inside
<body>):<p tabindex="-1" class="visually-hidden">Page Title</p>
This hidden tag must:- Have the same value as the page
<title>. - Possess a
tabindex="-1"attribute to allow programmatically moving focus using JavaScript. - Be visually hidden while remaining accessible to screen readers (for example, using the
.visually-hiddenclass).
- Have the same value as the page
- Dynamically move focus to this tag when changing pages (using the JavaScript
.focus()method).
Note
If the .visually-hidden class does not exist in the project, a class can be created to visually hide an element while keeping it available to screen readers:
.off-screen {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}