This is a basic navigation set up, using JavaScript to add the "current" class to a navigation link based on the current page's url.
To aid screen reader users, the script also adds aria-current="page" on the current link item.
In a further attempt at improving accessibility, I added tabindex="-1" to the current link item (see last line of script) . If users tab through the menu they will skip over the current link.
Is using tabindex in this way useful to screen readers, or more generally, an accessibility enhancement?
JS
window.addEventListener("DOMContentLoaded", () => {
let url_pathname = window.location.pathname
const link = document.querySelectorAll(".link")
link.forEach(linkCurrentItem => {
/*
A bit repetitious, but I wanted home page link to be just '/'
in the html.
If you have '/index.html' in the html then you can comment out
the first if statement and edit the second like so:
if (url_pathname === linkCurrentItem.getAttribute("href")) {
...
}
*/
if (url_pathname === linkCurrentItem.getAttribute("href", "/")) {
linkCurrentItem.classList.add("current")
}
if (
url_pathname === linkCurrentItem.getAttribute("href") &&
url_pathname !== linkCurrentItem.getAttribute("href", "/")
) {
linkCurrentItem.classList.add("current")
}
/* For screen readers */
if (url_pathname === linkCurrentItem.getAttribute("href")) {
linkCurrentItem.setAttribute("aria-current", "page")
// IS ADDING tabindex="-1" A GOOD IDEA?
linkCurrentItem.setAttribute("tabindex", "-1")
}
})
})
CSS
.link,
.link:visited {
color: blue;
text-decoration: none;
font-weight: 400;
font-size: 100%;
}
.current,
.current:visited {
color: black;
font-weight: 900;
font-size: 125%;
cursor: default;
}
HTML
<nav aria-label="main menu">
<ul>
<li><a class="link" href="/">Home</a></li>
<li><a class="link" href="/projects.html">Projects</a></li>
<li><a class="link" href="/blog.html">Blog</a></li>
<li><a class="link" href="/about.html">About</a></li>
<li><a class="link" href="/contact.html">Contact</a></li>
</ul>
</nav>