Setting an active menu item based on the current URL with jQuery

A simple client-side solution

This problem pops up over and over again when building websites - how do I determine the user’s current location so I can highlight the active section in the navigation menu? It’s such a basic need but the solution seems to be reinvented on every new build.

There are two main routes you can take when solving this problem in a dynamic manner, server side and client side. Solving this on the server side is nice because you’ll have a better handle on the page being requested, but it’s not always practical. With a little planning, it’s pretty straightforward to solve this on the client side using JavaScript (and optionally jQuery).

Let’s assume you have a basic navigation menu in your header and you want to change the background color of the current page you’re on.


Ideally, when you click on Tour and you’re taken to the Tour page, you’d like the menu to reflect your current location.

To do this using jQuery, we’re going to compare the href attribute of each menu link to the current browser URL and try to find a match. If a match is found, we’ll set that element to active by adding a class to the <li> element.


The net result of this very basic example looks like this


On every page load this script executes and compares the href of each menu link to the current page URL starting after the domain name and continuing forward for as many characters as exist in the href (similar to a startsWith() function). This allows for any sub-pages of “Tour” to also flag Tour as the active section for example, /tour/section2.html. When a match is found, the parent element - in this case an <li> - has a class of “active” added to it.

This solution can be found over at jsFiddle for use and is also embedded below. The main thing you’ll need to change for your own needs is the “.nav” selector on line 9 of the JavaScript. This should be modified to select the navigation element you want to process.

Note that the jsFiddle example won’t work because you can’t actually change the URL in the result window, but you can easily copy the code to an HTML file to test it out.

ITWorld DealPost: The best in tech deals and discounts.
You Might Like