Robert Ross Robert Ross - 1 year ago 106
jQuery Question

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

I have a bootstrap navbar in my 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 + '"]')

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

Can someone help me make this work properly


<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>
@Html.ActionLink("blah blah", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
<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>


Answer Source

Please try this:

$(document).ready(function () {
        $('ul.nav.navbar-nav').find('a[href="' + location.pathname + '"]').closest('li').addClass('active');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download