How to build accessible main navigation?
How to build accessible main navigation?
By Tim Dujardin
6 min read
This article contains a guide to building an accessible main navigation of a website in 5 steps. The key takeaways of this guide are HTML semantics, WAI-ARIA, CSS, and JS for accessibility.
- Authors
- Name
- Tim Dujardin
- linkedinTim Dujardin
- twitter@timdujardin
- Github
- githubtimdujardin
Introduction
Structuring a webpage is based on using the right semantic HTML, these semantics will provide all kinds of information necessary to process the page. Most of us know that semantics make a big difference on a level of SEO, but it also has a huge impact on accessibility. People with certain disabilities use assistive technology (AT) to process all that information, so it's essential to make sure everything is communicated in the right way.
In this article, I will zoom into the main navigation region of a webpage while keeping assistive technology in mind. An example of assistive technology through computer software is a screen reader. I will be using VoiceOver, the default screen reader on Mac, to illustrate examples.
If you are interested in more examples of assistive technology take a look at the AT list on atia.org.
These are some terms I use alternatively throughout the article:
Abbreviation | Term |
---|---|
a11y | Accessibility |
AT | Assistive Technology |
SR | Screen reader |
Screen readers
Screen readers use the accessibility tree instead of the regular DOM tree, which is basically the DOM tree from a (meaningful) semantic point of view. If you want to know how to inspect the a11y tree, you can take a look at the "What is an accessibility tree and how do I view it?" article.
Accessible in 5 steps
These are the steps I will guide you through:
- Identify the navigation region(s)
- Communicate the list of navigation items and their size
- Add multiple levels
- Highlight the active (sub)page
- Provide mobile support
1. Identify the navigation region(s)
To identify the navigation region on a webpage, I use the <nav>
element.
<nav>
<a href="/about-us">About us</a>
<a href="/products">Products</a>
<a href="/insights">Insights</a>
<a href="/contact">Contact</a>
</nav>
AT info: SRs have shortcuts and gestures to navigate by landmarks, so they don't need to go through the whole webpage over and over again when discovering a website.
2. Communicate the list of navigation items and their size
As a visual user, I see that the navigation consists of a list of 4 links, but a screen reader user won't hear a "List" announcement since the markup doesn't represent that. To create an equal experience for both users, wrap the navigation links in a <ul>
element.
AT info: When SRs navigate to a list element such as
<ul>
or<ol>
, they will announce "List # items". The same could be achieved through using WAI-ARIA rolelist
andlistitem
, but the rule of thumb is "use ARIA as a last resort". More information on "When should you use ARIA?".
<nav>
<ul>
<li><a href="/about-us">About us</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/insights">Insights</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
3. Add multiple levels
Multi-level support can be provided through 5 changes:
- Replace the
<a>
with a<button>
since the purpose of 'Products' is no longer navigation, but toggling the submenu. More info is in the "Buttons vs links" article. - Add
aria-expanded="false"
to the<button>
element to let the SR know that interacting with the button will expand another element. The visual representation is the arrow icon (<svg>
) in this scenario, since it's only visual I hide it for AT througharia-hidden="true"
. - The element expanding through interaction with the button is referenced by the
aria-controls
attribute.
<nav>
<ul>
<li><a href="/about-us">About us</a></li>
<li>
<button aria-expanded="false" aria-controls="products-level-2">
Products
<svg aria-hidden="true">...</svg>
</button>
<ul id="products-level-2" class="hidden">
<li><a href="/products/product1">Product 1</a></li>
<li><a href="/products/product2">Product 2</a></li>
</ul>
</li>
<li><a href="/insights">Insights</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
- Here is the first time JS comes into play: I use it to toggle the right
aria-expanded
value and to move the focus to the first actionable element within the referenced element. - Closing the referenced element must be done via the
ESC
key, which is the industry standard for keyboard accessibility.
AT info: The SR will announce "Products, collapsed, button" on focusing the initial state of the button. When I click the button, it will announce "Products, expanded, button" and move the focus dynamically to the referenced content.
class ExpandButton {
get isAriaExpanded() {
return this.#isAriaExpanded;
}
set isAriaExpanded(value) {
this.#isAriaExpanded = value;
this.el.setAttribute("aria-expanded", this.isAriaExpanded.toString());
if (this.isAriaExpanded) {
this.#ariaControlsElement?.classList.remove(this.#hiddenClass);
setTimeout(() => {
// focus on first actionable element within the ref element
this.#firstActionElement?.focus();
}, 10);
} else {
this.#ariaControlsElement?.classList.add(this.#hiddenClass);
}
}
initListeners() {
// Correctly toggle aria-expanded based on click interaction
this.clickHandler();
// Collapse the aria-controls element when blurred
this.collapseOnBlurHandler();
}
collapse() {
this.isAriaExpanded = false;
}
toggle() {
this.isAriaExpanded = !this.isAriaExpanded;
}
clickHandler() {
this.el.addEventListener("mousedown", (e) => {
e.preventDefault();
this.toggle();
});
this.el.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === "Space") {
e.preventDefault();
this.toggle();
}
});
}
collapseOnBlurHandler() {
if (this.el.classList.contains("mobile-menu-button")) {
return;
}
(this.#ariaControlsElement as HTMLElement).addEventListener(
"focusout",
(e: Event) => {
const currentTarget = e.currentTarget as HTMLElement;
requestAnimationFrame(() => {
if (!currentTarget.contains(document.activeElement)) {
this.collapse();
}
});
}
);
}
}
To instantiate the ExpandButton
class I have used an ExpandButtonFactory
(full code example in CodePen), this factory keeps track of all the ExpandButton
instances and adds a window keydown
listener for the ESC
key. This listener will provide the necessary collapsing mechanism when navigating by keyboard.
const menuItemButtons = ExpandButtonFactory.create(".expand-button");
4. Highlight the active (sub)page
4.1 Active page
Most websites provide an active state styling for current page links, but this will only cover the visual part of communicating this information. On a semantic level, I need to make use of an ARIA attribute called aria-current
.
AT info: The anchor element with attribute
aria-current="page"
will be announced as "Current page, link, About us" by the VoiceOver screen reader.
<nav>
<ul>
<li><a href="/about-us" aria-current="page">About us</a></li>
<li>
<button aria-expanded="false" aria-controls="products-level-2">
Products
<svg aria-hidden="true">...</svg>
</button>
<ul id="products-level-2" class="hidden">
<li><a href="/products/product1">Product 1</a></li>
<li><a href="/products/product2">Product 2</a></li>
</ul>
</li>
<li><a href="/insights">Insights</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
4.2 Active subpage
When the webpage contains multi-level main navigation, I can use the title
attribute on the parent link to announce that a sublevel item is the current page.
AT info: Now, when I navigate to the 'Products' link via my screen reader, I will hear "Products, link, Contains current page link" to indicate that the current page is inside its submenu.
<nav>
<ul>
<li><a href="/about-us">About us</a></li>
<li>
<button aria-expanded="true" aria-controls="products-level-2" title="Contains current page link">
Products
<svg aria-hidden="true">...</svg>
</button>
<ul id="products-level-2">
<li><a href="/products/product1" aria-current="page">Product 1</a></li>
<li><a href="/products/product2">Product 2</a></li>
</ul>
</li>
<li><a href="/insights">Insights</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
Important: Be careful with the usage of the
title
though, more info in the "Title attribute use and abuse" article.
5. Provide mobile support
The mobile navigation has a mobile menu button to trigger the <nav>
, so I used the same approach as with the multi-level navigation in step 3.
<header>
<button
class="mobile-menu-button" aria-expanded="false" aria-controls="main-nav">Mobile menu</button>
<nav id="main-nav" class="hidden-mobile">...</nav>
</header>
The easy part of using the ExpandButton
class is that I can reuse it for the mobile menu button which triggers the visibility of the mobile navigation.
const mobileMenuButton = ExpandButtonFactory.create(
".mobile-menu-button",
"hidden-mobile"
);
The final touch
The nice thing about using aria
attributes is that I don't need the extra is-active
classes to provide some styling. Just by targeting [aria-expanded]
I have a selector that provides me with the necessary information.
Same for [aria-current="page"]
and [aria-current="true"]
to style active navigation menu items when they respectively are or contain the current page link.
...
button {
&[aria-expanded="true"] > svg {
transform: rotate(180deg);
}
&[aria-expanded="false"] + ul {
opacity: 0;
height: 0;
}
}
...
CodePen
Finally, I add some styling to make it look more like the usual website navigation. The full code example is available on CodePen: Accessible main navigation.
Tips and tricks
<nav>
Handling multiple If the webpage contains multiple <nav>
elements, each <nav>
needs an aria-label
element to provide screen reader users with clear distinction.
AT info: SRs will list the following 2 landmarks respectively as "Main navigation" and "Product navigation", instead of 2 times "navigation".
// Main navigation
<nav aria-label="Main">
<ul>
<li><a href="/about-us">About us</a></li>
<li><a href="/products" aria-current="page">Products</a></li>
<li><a href="/insights">Insights</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
// Product navigation
<nav aria-label="Product">
<ul>
<li><a href="/product1">Product 1</a></li>
<li><a href="/product2">Product 2</a></li>
<li><a href="/product3">Product 3</a></li>
<li><a href="/product4">Product 4</a></li>
</ul>
</nav>
Upcoming events
Mastering Event-Driven Design
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tรผtรผncรผ, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! ๐ 18:00 โ ๐ช Doors open to the public 18:15 โ ๐ Letโs eat 19:00 โ ๐ข Getting Your Axe On Event Sourcing with Axon Framework 20:00 โ ๐น Small break 20:15 โ ๐ข Event-Driven Microservices - Beyond the Fairy Tale 21:00 โ ๐โโ๏ธ drinks 22:00 โ ๐ป See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many โmicroservices projectsโ fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.
| Coven of Wisdom - Utrecht
Go to page for Mastering Event-Driven DesignThe Leadership Meetup
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! ๐ 18:00 โ ๐ช Doors open to the public 18:15 โ ๐ Letโs eat 19:00 โ ๐ข First round of Talks 19:45 โ ๐น Small break 20:00 โ ๐ข Second round of Talks 20:45 โ ๐โโ๏ธ drinks 21:00 โ ๐ป See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!
| Coven of Wisdom - Amsterdam
Go to page for The Leadership MeetupCoven of Wisdom - Herentals - Spring `24 edition
Join us for an exciting web technology meetup where youโll get a chance to gain valuable insights and knowledge about the latest trends in the field. Donโt miss out on this opportunity to expand your knowledge, network with fellow developers, and discover new and exciting possibilities. And the best part? Food and drinks are on us! Johan Vervloet - Event sourced wiezen; an introduction to Event Sourcing and CQRS Join me on a journey into the world of CQRS and Event Sourcing! Together we will unravel the misteries behind these powerful concepts, by exploring a real-life application: a score app for the 'Wiezen' card game.Using examples straight from the card table, we will delve into the depths of event sourcing and CQRS, comparing them to more traditional approaches that rely on an ORM.We will uncover the signs in your own database that indicate where event sourcing can bring added value. I will also provide you with some tips and pointers, should you decide to embark on your own event sourcing adventure. Filip Van Reeth - WordPress API; "Are you talking to me?" What if the WordPress API could be one of your best friends? What kind of light-hearted or profound requests would it share with you? In this talk, I would like to introduce you to it and ensure that you become best friends so that together you can have many more pleasant conversations (calls). Wanna be friends? Please note that the event or talks will be conducted in Dutch. Want to give a talk? Send us your proposal at meetup.herentals@iodigital.com 18:00 - 19:00: Food/Drinks/Networking 19:00 - 21:00: Talks 21:00 - 22:00: Networking Thursday 30th of May, 18h00 - 22h00 CET iO Campus Herentals, Zavelheide 15, Herentals
| Coven of Wisdom Herentals
Go to page for Coven of Wisdom - Herentals - Spring `24 edition