Navbars

Vicente Soriano
3 min readJul 15, 2021

Letting our users know their current location in regards to the applications we build is part of providing a great user experience. Let’s say we have a navbar with some paths - “Home”, “Events”, and “Groups.”

The problem here is that we’re in the “events” page but our navbar is not indicating it or letting us know. One way to fix this is by using JavaScript in the console or script tag. The idea is to iterate through the items in the navbar until we find one that matches the current path and then style it to differentiate it from the other items in the list.

Getting the navbar items from the navbar

To get the list of the items in the navbar, we can use the querySelectorAll method. The items currently have the class attribute with the value, “nav-link.”

As we can see, it returns a NodeList that we’ll be able to iterate through. We gave the value of the NodeList to a variable navbarItems. As we iterate through navbarItems, we can see each element is just an anchor tag with a class, an href attribute to specify the URL to be linked to, and some inner text. Luckily for us, anchor tag elements have a pathname property that returns a string represting the pathname. In the following code, we will iterate through the navBarItems and log the element with their pathnames next to them using a loop.

Finding a match

Now that we know how to go through this list. As we go through the list, we check if the item is equal to the current page or path. To get the current path, we can use the pathname property from the location object. The following code is an example with the current URL being localhost:8000/events/.

As a reminder, the idea is to go through the items in the navbar list until we find one that matches the current path. If we find an item that does, we will change its styling to differentiate it from the others.

If we’re using Bootstrap and we prefer their example from the documentation, we just need to add “active” to the matching element’s class and set it’s aria-current attribute to “page”, like so.

Let’s say we’d like to add our own custom style to it, like changing the text color to green and its font-weight to bold. Instead of adding “active” to the element’s className(which is to style it using Bootstrap) we can style the element with its style attribute.

If we’re on the “events” path, the navbar should look this.

Thanks for reading! I hope this helps.

--

--