Twitter Bootstrap add active class to li

Viewed 151031

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.

16 Answers

There is a hitch with the accepted answer in some rare cases for bootstrap 4: In order to use the solution for relative paths like:

<ul class="navbar-nav nav-t">
   <li class="nav-item"><a href="index.php" class="nav-link">Home</a></li>
   <li class="nav-item"><a href="about.php" class="nav-link">About</a></li>
   <li class="nav-item"><a href="blog.php" class="nav-link">Blog</a></li>
   <li class="nav-item"><a href="info.php" class="nav-link">Info</a></li>
</ul>

Then you will find out that the code for:

 if (activePage == currentPage) {
      $(this).parent().addClass('active'); 
    } 

active page returns the whole url and current location returns the current href DOM Element value which is filename.php. To solve this just tweak the code a little by adding a method to correct this:

//... other js/jquery code
var activeMenuItemChanges=function () {
    function stripTrailingSlash(str) {
        if(str.substr(-1)=='/'){
            return str.substr(0, str.length -1);
        }
        return str;
    }
    // for cases where we do not use full url but relative file names in the href of ul>li>a tags:
    function getRelativeFileName(str){
        let page=str.substr(str.lastIndexOf('/')+1);
        if(page.length > 0){
            return page;
        }
        return 'index'|'index.php';
    }

    let url=window.location.pathname;

    let activeLocation=stripTrailingSlash(url);

    let activeFileName=getRelativeFileName(activeLocation);

    $('.nav-item a').each(function() {
        let currentLocation=stripTrailingSlash($(this).attr('href'));
        if(activeFileName==currentLocation){
            $(this).parent().addClass('active');
        }
    });
}
activeMenuItemChanges();

//... other js/jquery code
Related