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.
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.
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.