Dynamically Add Active Class to Links with jQuery

Posted on Thu, October 24, 2013 in Web Design, by Alum

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 <script></script> tag pair and you’re good to go. If you’d like to know what it does and why, read on.

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

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:

jQuery(document).ready(function($) ... }); 

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 ‘<a>’ 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:

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

Last step, we iterate though the matching links with <strong>.each()</strong> to apply the class ‘active’ to each.

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

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.

Tell Us About Your Project

Invalid phone number