Skip to content

Dynamically Add Active Class to Links with jQuery

By GRAYBOX Alumni

Here is a quick snippet that I've found useful on several occasions, particularly when you want to build out navigation dynamically and need a quick and dirty way to highlight the currently active page's link.

Below is the full code, just drop it on your page inside of a tag pair and you're good to go. If you'd like to know what it does and why, read on.

[code] jQuery(document).ready(function($) { jQuery("*").find("a[href='"+window.location.href+"']").each(function(){ jQuery(this).addClass("active"); //add additional code here if needed }) }); [/code] 

It's brief, but let's walk through what it's doing on the page as it never hurts to know what's going on if you want to modify, or to simply be aware of what's running on your site. First, we wrap the whole thing in .ready like so:

[code] jQuery(document).ready(function($) { ... }); [/code] 

This causes the script to fire when the page has reported back to the browser that all elements are loaded, this is important for two reasons, 1) to prevent this script from interacting before we have all our links in place, and 2) to prevent this script from interrupting the page during it's initial load. You can use the alias "$" instead of "jQuery" here, but I prefer to be explicit in my code so that we can avoid issues later on (and it's just a handy reminder that hey, we're using jQuery here). Next, we're going to use the .find() function to search for all ‘' tags on the page, and return to our script an array of links that point to the current page by using a pseudo selector with a bit of JS to fetch the current URL. The full function call looks like:

[code] ... jQuery("*").find("a[href='"+window.location.href+"']") ... [/code] 

Last step, we iterate though the matching links with .each() to apply the class 'active' to each.

[code] ... .each(function(){ jQuery(this).addClass("active"); //add additional code here if needed }) ... [/code] 

There you have it, class=—active— will now be applied to any link on the page that currently points to the current url. Keep in mind that you should try to achieve this through the CMS or server side script whenever possible to reduce the JS running in the client browser and minimize page size, but the effects on both here are minimal so this is a perfect way to deal with links outside of navigation, or if you're unable to achieve this with PHP (et al.) on your site.

If you're a developer come join us at an upcoming event to geek out with our team on all things code. Events might include lunch & learns on topics such as ecommerce trends, networking events on our roof decks, or meetups of local professionals.

Blog & Events

Featured Work