Vicky
Vicky

Reputation: 358

Set navbar current menu active

I am using asp.net 4.0 with bootstrap3. I used navbar in my master page, and i tried this jquery code to make current menu active. Below is the code

$('.nav li a').click(function (e) {
          
            var $this = $(this);
            if (!$this.hasClass('active')) {
                $this.addClass('active');
            }
          
        });

this works fine but when current menu page loads it is becoming inactive. How to set active for current menu?

Upvotes: 1

Views: 326

Answers (2)

Khazratbek
Khazratbek

Reputation: 1656

Another way (more complex) is:

First of all, your master page's design (navbar):

<li id="liContacts" runat="server">
    <a href="Contact.aspx">Contacts</a>
</li>

Master page code behind:

public String linkContacts
{
    get 
    {
        return "not_active";
    }
    set
    {
        liContacts.Attributes.Add("class", "" + value + "");
    }
}

Add following code to your Content page's header:

<%@ MasterType VirtualPath="~/MasterPage.master" %> <!-- change path to your master page //-->

Content page's code behind:

this.Master.linkContacts = "active";

Upvotes: 1

Orif Khodjaev
Orif Khodjaev

Reputation: 1102

You set css class to an element and then reload the page, so, changes are lost there. One of the ways to accomplish what you're trying to do is to add this js code to your master page (customize selector for your case):

$(document).ready(function() {
    $('#main-navbar .nav a[href="' + this.location.pathname + '"]').parent().addClass('active');
});  

Upvotes: 0

Related Questions