Skip to content
Advertisement

Add Active Navigation Class Based on URL

I’m trying to add an active class (i.e. class="active") to the appropriate menu list item based upon the page it is on once the page loads. Below is my menu as it stands right now. I’ve tried every snippet of code I could find in this regard and nothing works. So, can someone please explain simply where and how to add in javascript to define this task?

<ul id="nav">
    <li id="navhome"><a href="home.aspx">Home</a></li>
    <li id="navmanage"><a href="manageIS.aspx">Manage</a></li>
    <li id="navdocso"><a href="docs.aspx">Documents</a></li>
    <li id="navadmin"><a href="admin.aspx">Admin Panel</a></li>
    <li id="navpast"><a href="past.aspx">View Past</a></li>
</ul>

Here is an example of the javascript that I’m putting in my head tag in my site master. What am I doing wrong?

$(document).ready(function () {
    $(function () {
        $('li a').click(function (e) {
            e.preventDefault();
            $('a').removeClass('active');
            $(this).addClass('active');
        });
    });
});

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement