How to set Bootstrap navbar as Active for ASP.NET Site Master


Hmm.. It’s May 1st, 2016 and John Snow finally breathes again!!

Coming back to reality, I have faced a small problem earlier today with Bootstrap. I have a small ASP.NET web site, which uses a Master page (Site.Master). And I have added a Navbar in the master page so that it can be utilized from every pages that will be using the Site.Master.

Here is how my Navbar section looks in the Site.Master Page:

<div id="navbar" class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="~/">My Demo Site</a>
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="nav-collapse collapse">
<ul class="nav navbar-nav">
	<li><a href="~/">Home</a></li>
	<li><a href="~/DemoPage1.aspx">Demo 1</a></li>
	<li><a href="~/DemoPage2.aspx">Demo 2</a></li>
	<li><a href="~/DemoPage3.aspx">Demo 3</a></li>
</ul>
</div>
</div>
</div>
</div>
....

Very Basic.. Ha!

And now, I want to set the Nav class as Active for the pages I visit. As an example, if I go to Demo 1 page, then the Demo 1 Nav should get the active class turned on, For Demo 2, Demo 2 page should be active..

i.e. I want to set the class as ‘active’ to my navbar depending on the page I am on, dynamically.

After checking many useful postings through Google, I have found the following one as workable in my case:

$(document).ready(function () {
            var pageName = window.location.pathname;
            var newPageName = pageName;

            if (pageName.indexOf('/') == 0) {
                newPageName = pageName.substring(1, pageName.length);

                $.each($('#navbar').find('li'), function () {
                    var hrefVal = $(this).find('a').attr('href');

                    if (hrefVal.indexOf(newPageName) >= 0) {
                        $(this).addClass('active').siblings().removeClass('active');
                    }

                });
            }
        });

I have added this code in my Site.Master page and it worked like a Charm!! Kudos to Harry Potter 🙂