Twitter bootstrap + asp.net masterpages, how to set navbar item as active when user selects it?

VSP picture VSP · Sep 10, 2012 · Viewed 11k times · Source

We are in se same situation as question Make Twitter Bootstrap navbar link active, but in our case we are using ASP.net and MasterPages...

The thing is the navbar is defined at the masterpage and when you click a menuitem you are redirected to the corresponding child page so how would you do to change the navbar active item consecuently without replicating the logic in each child page? (Preferably without session variables and javascript only at master page)

Answer

VSP picture VSP · Sep 11, 2012

We solved it with the following function at Master Page:

 <script type="text/javascript">
        $(document).ready(function () {
            var url = window.location.pathname;
            var substr = url.split('/');
            var urlaspx = substr[substr.length-1];
            $('.nav').find('.active').removeClass('active');
            $('.nav li a').each(function () {
                if (this.href.indexOf(urlaspx) >= 0) {
                    $(this).parent().addClass('active');
                }
            });
        });
    </script>