how to set active class to nav menu from twitter bootstrap how to set active class to nav menu from twitter bootstrap jquery jquery

how to set active class to nav menu from twitter bootstrap


You can use this JavaScript\jQuery code:

// Sets active link in Bootstrap menu// Add this code in a central place used\shared by all pages// like your _Layout.cshtml in ASP.NET MVC for example$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');

It'll set the <a>'s parent <li> and the <li>'s parent <ul> as active.

A simple solution that works!


Original source:

Bootstrap add active class to li


it is a workaround. try

<div class="nav-collapse">  <ul class="nav">    <li id="home" class="active"><a href="~/Home/Index">Home</a></li>    <li><a href="#">Project</a></li>    <li><a href="#">Customer</a></li>    <li><a href="#">Staff</a></li>    <li  id="demo"><a href="~/Home/demo">Broker</a></li>    <li id='sale'><a href="#">Sale</a></li>  </ul></div>

and on each page js add

$(document).ready(function () {  $(".nav li").removeClass("active");//this will remove the active class from                                       //previously active menu item   $('#home').addClass('active');  //for demo  //$('#demo').addClass('active');  //for sale   //$('#sale').addClass('active');});


I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.

$(document).ready(function () {             $(function(){        var current_page_URL = location.href;        $( "a" ).each(function() {            if ($(this).attr("href") !== "#") {                var target_URL = $(this).prop("href");                    if (target_URL == current_page_URL) {                        $('nav a').parents('li, ul').removeClass('active');                        $(this).parent('li').addClass('active');                        return false;                    }            }        }); }); });