Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Bootstrap add active class to li

Using twitter bootstrap, and I need to initiate active class to the li portion of the main nav. Automagically. We use php not ruby.

Sample nav :

<ul class="nav">     <li><a href="/">Home</a></li>     <li><a href="/forums">Forums</a></li>     <li><a href="/blog">Blog</a></li>     <li><a href="/faqs.php">FAQ's</a></li>     <li><a href="/item.php">Item</a></li>     <li><a href="/create.php">Create</a></li> </ul> 

Bootstrap code is as follows:

<li class="active"><a href="/">Home</a></li> 

So just need to figure out how to append the class active to the current page. Have looked thru nearly every answer on Stack, with no real joy.

I had played with this:

/*menu handler*/ $(function(){     var url = window.location.pathname;       var activePage = url.substring(url.lastIndexOf('/')+1);     $('.nav li a').each(function(){           var currentPage = this.href.substring(this.href.lastIndexOf('/')+1);          if (activePage == currentPage) {             $(this).parent().addClass('active');          }      }); }) 

But no joy.

like image 563
422 Avatar asked Jul 18 '12 02:07

422


People also ask

How do I change the active class in bootstrap?

To set an active class in your bootstrap navbar, you can use ng-controller(NavigationController) to set bootstrap navbar active class with AngularJS. To run a single controller outside ng-view. You can set class= “active” when the angular route is clicked.

How do you add and remove active class on click?

removeClass("active"); $(this). addClass("active"); }); This will remove the active class when clicked then add it to the current item being clicked.


2 Answers

For Bootstrap 3:

var url = window.location; // Will only work if string in href matches with location $('ul.nav a[href="'+ url +'"]').parent().addClass('active');  // Will also work for relative and absolute hrefs $('ul.nav a').filter(function() {     return this.href == url; }).parent().addClass('active'); 

Update

For Bootstrap 4:

var url = window.location; // Will only work if string in href matches with location $('ul.navbar-nav a[href="'+ url +'"]').parent().addClass('active');  // Will also work for relative and absolute hrefs $('ul.navbar-nav a').filter(function() {     return this.href == url; }).parent().addClass('active'); 
like image 121
Imtiaz Avatar answered Oct 03 '22 04:10

Imtiaz


We managed to fix in the end:

/*menu handler*/ $(function(){   function stripTrailingSlash(str) {     if(str.substr(-1) == '/') {       return str.substr(0, str.length - 1);     }     return str;   }    var url = window.location.pathname;     var activePage = stripTrailingSlash(url);    $('.nav li a').each(function(){       var currentPage = stripTrailingSlash($(this).attr('href'));      if (activePage == currentPage) {       $(this).parent().addClass('active');      }    }); }); 
like image 23
422 Avatar answered Oct 03 '22 04:10

422