Add Active Navigation Class Based on URL

The reason this isn’t working is because the javascript is executing, then the page is reloading which nullifies the ‘active’ class. What you probably want to do is something like:

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

There are some cases in which this won’t work (multiple similarly pointed links), but I think this could work for you.

Leave a Comment