Md. Masudur Rahman
Md. Masudur Rahman

Reputation: 1078

Navigation bar active class not working correctly when route to another link

How do I set active class when a link is clicked? The Link1 does not get the active class when it is clicked. The codes are given below: HTML Part:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav" id="nav">
        <li id="home" class="active"><a href="/Home/Index">Home</a></li>
        <li id="skill"><a href="/Home/GoToLink1">Link1</a></li>
   </ul>
</div>

I have also used JQuery:

<script>
$(document).ready(function () {
    $('#nav li a').on('click', function () {
        $(this).parent().parent().find('.active').removeClass('active');
        $(this).parent().addClass('active');
    });
});
</script>

When I clicked any link, the active property not works correctly.

Upvotes: 0

Views: 1135

Answers (1)

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

When you redirect to new page dynamic state are not preserved. Get current location and then iterate through the nav menus. Which link is matched with current location make that active like below. Hope it helps.

<script>
    $(document).ready(function () {
        var location = window.location.href;
        $('#nav li a').each(function(){
            if(location.indexOf(this.href)>-1) {
               $(this).parent().addClass('active');
            }
        });
    });
</script>

Upvotes: 2

Related Questions