Learn how to highlight the currently active page in your website’s navigation bar/menu.
A common website feature is to highlight the current page menu item when the user navigates from page to page.
Here’s how to do that with vanilla JavaScript.
Step 1: A simple menu
<nav class="navbar">
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
Step 2: CSS styling
Some minimal CSS styling. The important part here is the .current
class, which is what we will add to the current active page item, in step 3:
.navbar {
background-color: #111;
padding: 1rem;
}
.navbar a {
text-decoration: none;
color: white;
padding: 1rem;
}
.current {
color: #df3e23;
}
Step 3: JavaScript
This code will look for the current page URL and then add the current
class to the corresponding menu item:
const current = 0;
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].href === document.URL) {
current = i;
}
}
document.links[current].className = 'current';