If I'm building a single page web app, what should happen to
focuswhen the user clicks some navigation?
This is a video I shot a while back, but the question comes up so often I wanted to re-share here on dev.to—plus it's a good excuse to write my first post 😁
Typically in a single page app you'll have a structure that looks roughly something like this:
<nav>
<a href="/">Home</a>
<a href="/cart">Shopping Cart</a>
<a href="/settings">Settings</a>
</nav>
<main>
<!-- some content -->
</main>
Because it's a single page app, clicking on a link won't do a hard refresh. Instead, it will trigger a route change which usually uses a bit of AJAX to fetch some more data and populate the <main> content area.
For a sighted user this is all good—but what if I'm a non-sighted user navigating with a screen reader? I may not know that the new content has been added to the page (maybe I was expecting a hard refresh) and there's no indication that I should navigate back to the <main> area.
One easy way to improve this experience is to find a good heading in the newly loaded content and direct focus to it. The easiest way to pull this off is to give the heading a tabindex of -1 and call its focus() method.
<main>
<h2 tabindex="-1">Welcome to your shopping cart</h2>
</main>
<script>
// Assuming this gets called every time new content loads...
function onNewPage() {
var heading = document.querySelector('h2');
heading.focus();
// You can also update the page title :)
document.title = heading.textContent;
}
</script>
A screen reader will then announce the new heading, as well as the main landmark area that it's contained within. Note that you probably don't want to do this focus management when a user first arrives at your site—you would only want to do it for subsequent navigation, like when they click a link.
Hope you enjoyed this post! It's an easy trick that could make a big difference for some of your users. And if you're interested in more a11y screencasts check out my playlist over on the YouTubes 📺
✌️
Latest comments (12)
This article on managing focus for accessibility is a valuable resource for web developers and designers. cricketbuzz.com id login
I like your post and all you share with us is up to date and quite informative . Sky exchange login ID provider
What is important to consider when designing focus? negative energy cleansing spell
Great post. I think if I'm going to start learning a11y, it's going to come in bite-sized chunks like this. Thanks for your work!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.