How to Add Active Navigation Class Based on URL

By FoxLearn 2/16/2024 9:46:12 AM   258
If you got a problem with highlight the active link in a navigation menu when selected, this example might help you solve it.

Our goal is to add the active attribute to the li tag that is currently selected

<ul class="nav sidebar-menu">
    <li class="active">
        <a href="/Home">
            <i class="menu-icon glyphicon glyphicon-home"></i>
            <span class="menu-text"> Dashboard</span>
        </a>
    </li>
    <li>
        <a href="#" class="menu-dropdown">
            <i class="menu-icon fa fa-table"></i>
            <span class="menu-text"> Category</span>
            <i class="menu-expand"></i>
        </a>
        <ul class="submenu">
            <li>
                <a href="/Company">
                    <span class="menu-text">Company</span>
                </a>
            </li>
            <li>
                <a href="/Account">
                    <span class="menu-text">Account</span>
                </a>
            </li>
        </ul>
    </li>
</ul>

To active navigation class base on url, you can use the script below

<script>
    $('li > a').click(function () {
        $('li').removeClass();
        $(this).parent().addClass('active');
    });
</script>