Robert Ross Robert Ross - 13 days ago 7
jQuery Question

MVC Bootstrap Navbar - active class stays to just one <li> element

I have a bootstrap navbar in my asp.net mvc app, and all I am trying to do is to change the active class to the currently selected element from the navbar menu.

I managed to partly achieve this by using the following jquery :

$(document).ready(function () {
$('ul.nav.navbar-nav').find('a[href="' + location.pathname + '"]')
.closest('li').addClass('active');
$(this).siblings().removeClass('active');
});


After implementing this both of my navbar links are highlighter. At first, only the one with the default
active
class, then the one I click to some other link It also becomes highlighter, but the default
active
still stays active, so I end up with two active links.

Can someone help me make this work properly

Bootstrap:

<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("blah blah", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("blah", "Create", "Todoes")</li>
<li class="active">@Html.ActionLink("ALL", "Index", "Todoes")</li>
<li>@Html.ActionLink("blah2", "", "Todoes")</li>
<li>@Html.ActionLink("blah3", "", "Todoes")</li>




</ul>
</div>
</div>

Answer

Please try this:

$(document).ready(function () {
        $('li').each(function(){
               $(this).removeClass('active');
        });
        $('ul.nav.navbar-nav').find('a[href="' + location.pathname + '"]').closest('li').addClass('active');
});