30

I'm new to the twitter bootstrap. Using there navigation menus . I'm trying to set active class to selected menu. my menu is -

<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="broker"><a href="~/Home/Broker">Broker</a></li>
    <li><a href="#">Sale</a></li>
  </ul>
</div>

I tried following thing after googling on this that i have to set active class on each page from menu like as--

<script>
  $(document).ready(function () {
    $('#home').addClass('active');
  });
</script>

but problem for above is that i set home menu selected by default. Then it always get selected. Is there any other way to do this ? , or which i can generalize and keep my js in layout file itself?

After executing application my menu looks - enter image description here

after clicking on other menu item i get following result- enter image description here

And i added following scripts on Index view and Broker view ---

<script>
  $(document).ready(function () {
    $('#home').addClass('active');
  });
</script>

<script>
  $(document).ready(function () {
    $('#broker').addClass('active');
  });
</script>

respectively.

Arnold Gandarillas
  • 3,896
  • 1
  • 30
  • 36
Priyanka
  • 2,802
  • 14
  • 55
  • 88

13 Answers13

82

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

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • also you can add st like this: `$('nav a').parents('li,ul').removeClass('active');` to automatically remove any remaining 'active' if needed – bubak Jul 13 '15 at 13:20
  • This isn't working for me so I'm curious to know what I'm doing wrong. My app is using web forms and I put this in the head section of my master page file. – PongGod Sep 24 '17 at 00:42
  • Great solution and works nice with dropdowns. I tried thousands other solution but this one is the best – kanlukasz Mar 30 '20 at 15:56
  • 1
    By far the easiest and best solution for this. Just brilliant! – user441521 Apr 06 '20 at 17:19
29

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');
});
Karthick Nagarajan
  • 1,327
  • 2
  • 15
  • 27
Dakait
  • 2,531
  • 1
  • 25
  • 43
  • 2
    thanks dakait. It solve my problem. But the thing is that i have to write script on each web pages then its difficult to maintain if my web pages increases. Is there any other way then i can generalize the script and keep in layout or may be by using any css property we an do this ? – Priyanka Feb 26 '13 at 06:45
  • @Priyanka i was in the same situation yesterday i solved the problem using the `localStorage` which is kind of a workaround too but then i dont have to write the js on each page. the reason is page gets reloaded and from the `localStorage` i retrieve the clicked `li`'s id and apply class to it. if i find a better solution ill update the answer... P.S you may mark the answer correct since it solved your problem `:p` – Dakait Feb 26 '13 at 06:53
5

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;
                    }
            }
        }); }); });
Mirko
  • 51
  • 1
  • 1
2

For single-page sites where the menu items simply jump down to other sections of the page, this simple solution works for me:

$('.nav li').on('click', function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
  });
Luke Green
  • 59
  • 5
1

You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:

<body class="nav-1-on">

Then this css:

.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
     // set your styles here
}

The NAV element:

<ul>
  <li class="nav-1"><a href="#">Home</a></li>
  <li class="nav-2"><a href="#">Services</a></li>
  <li class="nav-3"><a href="#">About</a></li>
  <li class="nav-4"><a href="#">Contact</a></li>
</ul>
#

Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.

Billy Moat
  • 20,792
  • 7
  • 45
  • 37
1
<div class="nav-collapse">
                <ul class="nav">
                    <li class="home"><a href="~/Home/Index">Home</a></li>
                    <li class="Project"><a href="#">Project</a></li>
                    <li class="Customer"><a href="#">Customer</a></li>
                    <li class="Staff"><a href="#">Staff</a></li>
                    <li class="Broker"><a href="~/Home/Broker">Broker</a></li>
                    <li class="Sale"><a href="#">Sale</a></li>
                </ul>
</div>

then for each page you add this:

//home

 $(document).ready(function () {
        $('.home').addClass('active');
    });

//Project page

$(document).ready(function () {
            $('.Project').addClass('active');
        });

//Customer page

 $(document).ready(function () {
                $('.Customer').addClass('active');
            });

//staff page

 $(document).ready(function () {
                $('.Staff').addClass('active');
            });
anyavacy
  • 1,618
  • 5
  • 21
  • 43
1
<div class="nav-collapse">
                <ul class="nav">
                    <li class="home"><a href="~/Home/Index">Home</a></li>
                    <li class="Project"><a href="#">Project</a></li>
                    <li class="Customer"><a href="#">Customer</a></li>
                    <li class="Staff"><a href="#">Staff</a></li>
                    <li class="Broker"><a href="~/Home/Broker">Broker</a></li>
                    <li class="Sale"><a href="#">Sale</a></li>
                </ul>
</div>

$('ul.nav>li.home>a').click();  // first. same to all the other options changing the li class name 
Apeto
  • 11
  • 2
1

For single page sites, the following is what I used. It not only sets the active element based on what's been clicked but it also checks for a hash value within the URL location on initial page load.

$(document).ready(function () {

    var removeActive = function() {
        $( "nav a" ).parents( "li, ul" ).removeClass("active");
    };

    $( ".nav li" ).click(function() {
        removeActive();
        $(this).addClass( "active" );
    });

    removeActive();
    $( "a[href='" + location.hash + "']" ).parent( "li" ).addClass( "active" );

});
Bill Christo
  • 1,223
  • 9
  • 8
1

For those using Codeigniter, add this below your sidebar menu,

<script>
    $(document).ready(function () {
        $(".nav li").removeClass("active");
        var currentUrl = "<?php  echo current_url();  ?>";
        $('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
    });
</script>
Martin Mbae
  • 1,108
  • 1
  • 16
  • 27
0
(function (window) {
bs3Utils = {}
bs3Utils.nav = {
    activeTab: function (tabId) {
        /// <summary>
        /// 设置需要展现的tab
        /// </summary>
        /// <param name="tabId"></param>
        $('.nav-tabs a[href="#' + tabId + '"]').tab('show');
    }
}
window.bs3Utils = bs3Utils;
})(window);

example:

var _actvieTab = _type == '0' ? 'portlet_tab2_1' : 'portlet_tab2_2';
            bs3Utils.nav.activeTab(_actvieTab);
                        <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#portlet_tab2_1" data-toggle="tab">箱-单灯节点 </a>
                        </li>
                        <li>
                            <a href="#portlet_tab2_2" data-toggle="tab">箱-灯组节点 </a>
                        </li>

                    </ul>
Ravi Mehta
  • 454
  • 1
  • 8
  • 20
YanZhiwei
  • 1
  • 1
0
$( ".nav li" ).click(function() {
        $('.nav li').removeClass('active');
        $(this).addClass('active');
    });

check this out.

Hardik Gajjar
  • 1,024
  • 12
  • 27
0

I am using Flask Bootstrap. My solution is a little bit simpler because my template already receives the option or choice as a parameter from Flask.

var choice = document.getElementById("{{ item_kind }}");
choice.className += "active";

First line, js code gets the element. So, you should identify each of the elements with a id. I'll show an example below. Second line, you add the class active. You can see html ids below.

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav"> 
        <li>
            <a id="speed" href="{{ url_for('list_gold_per_item',item_kind='speed',level='2') }}">
                <h2>Speed</h2>
            </a>
        </li>
        <li>
            <a id="life" href="{{ url_for('list_gold_per_item',item_kind='life',level='3') }}">
                <h2>Life</h2>
            </a>
        </li>
    </ul>
</div>
user83655
  • 334
  • 2
  • 4
-1

I just added a custom class to the ul section named target-active

<ul class="nav navbar-nav target-active">
    <li><a href="/">HOME</a></li>
    <li><a href="find-truck">FIND A TRUCK</a></li>
    <li><a href="our-service">OUR SERVICES</a></li>
    <li><a href="about-us">ABOUT US</a></li>
</ul>

If each li tags click get a new page from different place or same place, no need to add jquery removeClass function.

Add simple one line jquery code to each page to get your desired result

1st link page

$(function(){
    $(".target-active").find("[href='/']").parent().addClass("active");
});

2nd link page

$(function(){
    $(".target-active").find("[href=find-truck]").parent().addClass("active");
});

3rd link page

$(function(){
    $(".target-active").find("[href=our-service]").parent().addClass("active");
});

4th link page

$(function(){
    $(".target-active").find("[href=about-us]").parent().addClass("active");
});
sh6210
  • 4,190
  • 1
  • 37
  • 27