Design Workflow Blog

Automated navigation active state

Simple Javascript snippet for automatically giving items a selected state.

Example of an active state in a website's navigation.

Having an active state for the current page in your navigation helps with usability, for your users to know where they are within your website’s architecture. Setting it up however, can get complicated. You can select it manually when creating your page in your backend system/CMS, or set up a complex menu system to match up your pages.

After years of having to deal with this on websites, I’ve come up with a technique that I wish I would have thought of sooner: a few lines of Javascript to automatically set an active state on links based on the current URL.

The code

The code is pretty straightforward: it finds all links on the current page and adds an “on” class to the link when it matches the current URL:

var currentURL = window.location.href; var navItems = document.querySelectorAll('a'); function matchExact(r, str) { var match = str.match(r); return match && str === match[0]; } for (var i = 1; i < navItems.length; ++i) { if (matchExact(currentURL.match(navItems[i].href), currentURL)) { navItems[i].classList.add("on"); } }

This approach works with any kind of navigation as it applies to the root of the link itself. And your navigation is likely the only thing that has a link to the page you are currently on!

You then set what the active state looks like via your CSS:

a { color: #0b72c7; &.on { color: #444; } }

Extending it

If you need to, you can modify the code to target only your navigation. And change it to use the container around the link to apply your CSS class.

If you have a dropdown nav or subnav and you want to show both the current page and its parent as active, one way to do it is by utilizing the ul menu structure to determine the parent link and add an active state to it as well.

Check out the Starter components template that includes this technique as well as others to help with your web setup.

Photo of Ovi Demetrian Jr Ovi Demetrian Jr
Designing and building on the web for over 15 years