admin管理员组

文章数量:1192356

This is a code of HTML that I created for navigation bar using bootstrap.

<div id="menu">
    <ul class="nav navbar-nav">
        <li class="active"><a href="index.html">Home</a></li>
        <li><a href="#">Gallery</a></li>
        <li><a href="#">videos</a></li>
        <li><a href="#">Comment</a></li>
        <li><a href="#">About</a></li>
        <li ><a href="contact_us.html">Contact</a></li>
    </ul>
</div>

Now I need to add this li's active class dynamically for menu items when that page is open.

I just check these two stackoverflow question : one | two

But I couldn't figure this out.

This is my javascript -

$('#menu > ul.navbar-nav li').click(function(e) {
    $('.navbar li.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
});

Hope someone will help me out. Thank you.

This is a code of HTML that I created for navigation bar using bootstrap.

<div id="menu">
    <ul class="nav navbar-nav">
        <li class="active"><a href="index.html">Home</a></li>
        <li><a href="#">Gallery</a></li>
        <li><a href="#">videos</a></li>
        <li><a href="#">Comment</a></li>
        <li><a href="#">About</a></li>
        <li ><a href="contact_us.html">Contact</a></li>
    </ul>
</div>

Now I need to add this li's active class dynamically for menu items when that page is open.

I just check these two stackoverflow question : one | two

But I couldn't figure this out.

This is my javascript -

$('#menu > ul.navbar-nav li').click(function(e) {
    $('.navbar li.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
});

Hope someone will help me out. Thank you.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Aug 12, 2014 at 3:55 user3733831user3733831 2,92610 gold badges39 silver badges73 bronze badges 3
  • 1 you have a problem in $('.navbar li.active').removeClass('active'); it should be $('.navbar-nav li.active').removeClass('active'); – Arun P Johny Commented Aug 12, 2014 at 3:58
  • also there is no need for the if since you are removing the active class in the click handler - jsfiddle.net/arunpjohny/tj38Lv63/1 – Arun P Johny Commented Aug 12, 2014 at 4:00
  • Now active class is adding to menu items. but its corresponding page is not loading... – user3733831 Commented Aug 12, 2014 at 4:05
Add a comment  | 

9 Answers 9

Reset to default 5

Since you are using Bootstrap, include the defult javascript plugins bootstrap.js or the minified bootstrap.min.js you can have menus items dynamically actived by adding data-toggle="tab" to your li elements like this

<div id="menu">
    <ul class="nav navbar-nav">
        <li data-toggle="tab"><a href="index.html">Home</a></li>
        <li data-toggle="tab"><a href="#">Gallery</a></li>
        <li data-toggle="tab"><a href="#">videos</a></li>
        <li data-toggle="tab"><a href="#">Comment</a></li>
        <li data-toggle="tab"><a href="#">About</a></li>
        <li data-toggle="tab"><a href="contact_us.html">Contact</a></li>
    </ul>
</div>

As written in the official document, check here

You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element. Adding the nav and nav-tabs classes to the tab ul will apply the Bootstrap tab styling, while adding the nav and nav-pills classes will apply pill styling.

You may try this (DEMO):

$('#menu > ul.nav li a').click(function(e) {
    var $this = $(this);
    $this.parent().siblings().removeClass('active').end().addClass('active');
    e.preventDefault();
});

Btw, you should target the <a> instead of li. You may need to retrieve the href value and $(this).attr('href') will return it but you can do it either way, anyways.

Also, this will only handle highlighting the active item but you need to add code to load the clicked page and hope you'll do it using ajax and you know how to do it.

Update:

If you want to load the clicked item/page normally (without using JavaScript/ajax) then you need to remove e.preventDefault() but in this case this code won't highlight the active li and you need to do it from server side and other 3 answers are also given according to your current question which is about highlighting the current clicked item, you didn't mention anything about page loading and I assumed you are doing it using ajax and so did others as well (I think so).

Update for Ajax:

$('#menu > ul.nav li a').click(function(e) {
    var $this = $(this);
    $this.parent().siblings().removeClass('active').end().addClass('active');
    e.preventDefault();

    // Load the page content in to element
    // with id #content using ajax (There are other ways)
    $('#content').load($this.href());
});

Read more about it on jQuery website.

The solution is simple and no need from server side or ajax, you only need jQuery and Bootstrap. On every page add ID to -body- tag . Use that ID to find -a- tag that contains page name(value of -a- tag).

Example:

page1.html

<body id="page1">
<ul class="nav navbar-nav">
 <li><a href="page1.html">Page1</a></li>
 <li><a href="page2.html">Page2</a></li>
</ul>
<script src="script.js"></script>
</body>

page2.html

<body id="page2">
<ul class="nav navbar-nav">
 <li><a href="page1.html">Page1</a></li>
 <li><a href="page2.html">Page2</a></li>
</ul>
<script src="script.js"></script>
</body>

script.js

    $(function () {
        $("#page1 a:contains('Page1')").parent().addClass('active');
        $("#page2 a:contains('Page2')").parent().addClass('active');
     });

Big thanks to Ben! YouTube

I think this line will fix the problem

You are saying

$('.navbar li.active').removeClass('active');

But there is no element which has the class .navbar you should just say .nav.

$('.nav li.active').removeClass('active');

DEMO

Recently, I came across the same problem. I wanted to dynamically add the active class, the aria-current tag, and change the title of the page, whenever I would click on a different page.

Below is my html navbar:

<div class="navbar-nav">
    <a class="nav-link active" aria-current="page" href="index.php">Home</a>
    <a class="nav-link" href="flyers.php">Flyers</a>
    <a class="nav-link" href="promotions.php">Promotions</a>
    <a class="nav-link" href="grocery.php">Grocery</a>
    <a class="nav-link" href="contact.php">Contact</a>
</div>

The jquery iterates through all the <a> tags using the .each() function (a[href*=".php"] selects all <a> tags with an href attribute that contains a .php ). Then, it checks if the page's url includes the specific href of the current page (using window.location), which shows that it's been clicked. If it does, then it removes the active class and the aria-current attribute from all the links, and then adds it to the current page. It also takes the text of the title, and adds that to the title tag.

$(document).ready(function() {
    $('.navbar-nav a[href*=".php"]').each(function() {
        if (String(location).includes($(this).attr('href'))) {
            $('a.nav-link.active').removeAttr('aria-current');
            $('a.nav-link.active').removeClass('active');
            $(this).addClass('active');
            $(this).attr('aria-current', 'page');
            document.title = $(this).text().trim();
        }
    });
});

Working Js:

$(document).ready(function () {
        $('ul.nav > li').click(function (e) {
            e.preventDefault();
            $('ul.nav > li').removeClass('active');
            $(this).addClass('active');                
        });            
    });

DEMO Bootstrap Navbar

I have used:

$('ul.nav > li').removeClass('active');

Instead of:

$('.navbar li.active').removeClass('active');

Add these line to onen page:

var test = $(this).find("a");
test.trigger('click');

Update

This one is also working: window.location.href=$(this).find("a").attr('href');

setTimeout(function(){
       window.location.href=$(this).find("a").attr('href');
},1000);//redirection after interval

Here is my solution

$(document).ready(function () {
    $('.nav li a').click(function() {
        var $this = $(this);
        $this.parent().siblings().removeClass('active').end().addClass('active');
    });
});

No need to wrap the nav with any id.

I wrote this as I found the tab index didn't actually change the link to another file but just applied the css.

The code:

$('#home a:contains("Home")').parent().addClass("active");

Didn't work at all in my environment, bit of head scratching later and devised this.

Solution: Get the pathname and split it by "/" sample url: https://example.com/microsite/map.html will result in a list like this (based on sample url and setup i.e a microsite on the server with its own html files): ,microsite, map.html with a length of 3 get the items and switch the values:

    $(function(){
      let pathParts = window.location.pathname.split(/);
      let yourLink = pathParts[2] // in this example
      switch(yourLink){
         case: 'index.html':
         $('a:contains("Home")').parent().addClass("active");
         break;
         case: 'about.html':
         $('a:contains("About")').parent().addClass("active");   
         break;
         default:
         $('a:contains("Home")').parent().addClass("active"); 
         // if yourLink is empty then default to the home page
         }
     });

Why not change the style of the class altogether?

Easily done with javascript:

document.getElementsByClassName('classname').style.property.value

本文标签: javascriptAdd active class dynamically to bootstrap menu and opening its pageStack Overflow