5

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.

Community
  • 1
  • 1
user3733831
  • 2,886
  • 9
  • 36
  • 68
  • 1
    you have a problem in `$('.navbar li.active').removeClass('active');` it should be `$('.navbar-nav li.active').removeClass('active');` – Arun P Johny Aug 12 '14 at 03:58
  • also there is no need for the `if` since you are removing the `active` class in the click handler - http://jsfiddle.net/arunpjohny/tj38Lv63/1/ – Arun P Johny Aug 12 '14 at 04:00
  • Now active class is adding to menu items. but its corresponding page is not loading... – user3733831 Aug 12 '14 at 04:05

9 Answers9

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.

Jinhai ZHOU
  • 59
  • 1
  • 5
4

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 Alpha
  • 143,660
  • 29
  • 287
  • 307
4

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

Filip Gjorgjevikj
  • 1,367
  • 13
  • 11
  • 1
    If you're going to go this route, you can opt for a pure CSS solution instead of relying on JS. Add the IDs and HREF class to your declarations. This will work as long as your page IDs and unique nav link classes are static. – Roralee Sep 28 '17 at 14:33
2

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

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
1

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();
        }
    });
});
Dharman
  • 30,962
  • 25
  • 85
  • 135
Samex
  • 13
  • 5
0

Why not change the style of the class altogether?

Easily done with javascript:

document.getElementsByClassName('classname').style.property.value
Wolfgang
  • 1,328
  • 2
  • 8
  • 11
0

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
Manwal
  • 23,450
  • 12
  • 63
  • 93
0

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.

HTML Man
  • 937
  • 4
  • 16
  • 40
0

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
         }
     });
David Fleeman
  • 2,588
  • 14
  • 17