Adding an active class to nav links based on URL with jQuery Address

3 min read

I recently had to build a WordPress site for a client that was entirely AJAX in terms of navigation. By that I mean  that there is never a page reload when navigating through the site.

One of the challenges here was applying the usual “active” class to the relevant navigation link depending on which page the user is viewing. Because the header never gets reloaded, this needs to be done from within the jQuery.address.change function of jQuery Address. I won’t go in to detail about jQuery Address here, but the same concepts will apply for any other deep-linking / history solution that you are using.

Here are the steps I used. Bear in mind that with this technique, you need to provide the absolute path to your pages here, rather then just the relative paths. So your navigation would look something like –

1.  Assign the domain / “home page” URL to a variable

2.  Loop through the nav links, add a value for data-path, and add ‘active’ class

So what this does is it adds the attribute “data-path” to each of the nav links, and gives this attribute a value of whatever comes after the “base” URL. Because we are using jQuery Address, we have the (event.value) variable to play with. This value is automatically set to be whatever is after the “base” value too, which means we can now check to see if these values equal each other. If they do, the active class is added to the link. Remember, this function resides inside the jQuery.address.change function, so it will be run every time a new link is clicked.

Contact


Want to work with me or the Lab19 team? Great news! Reach me using the relevant links below: