[jquery] Twitter Bootstrap add active class to li

I had the same problem, and this is what I added in my app launch script, and it worked smoothly. Here is the javascript

$(document).ready(function($){
  var navs = $('nav > ul.nav');

  // Add class .active to current link
  navs.find('a').each(function(){

    var cUrl = String(window.location).split('?')[0];
    if (cUrl.substr(cUrl.length - 1) === '#') {
      cUrl = cUrl.slice(0,-1);
    }

    if ($($(this))[0].href===cUrl) {
      $(this).addClass('active');

      $(this).parents('ul').add(this).each(function(){
        $(this).parent().addClass('open');
      });
    }
  });
});

And the corresponding HTML is shown below. I'm using CoreUI, a phenomenal open source admin template and has support for many front end frameworks like Angular, plain bootstrap, Angular 4 etc.

<div class="sidebar">
<nav class="sidebar-nav open" >
    <ul class="nav" id="navTab" role="tablist">
        <li class="nav-item">
            <a class="nav-link"    href="/summary"><i class="icon-speedometer"></i> Dashboard </a>
        </li>
        <li class="nav-item">
            <a class="nav-link"    href="/balanceSheet"><i class="icon-chart"></i> Balance Sheet </a>
        </li>
        <li class="divider"></li>
        <li class="nav-title border-bottom">
            <p class="h5 mb-0">
                <i class="icon-graph"></i> Assets
            </p>
        </li>
     </ul>
  </nav>
</div>

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? What is the hamburger menu icon called and the three vertical dots icon called? Changing text color of menu item in navigation drawer How to get selected value of a dropdown menu in ReactJS Android custom dropdown/popup menu Creating a Menu in Python How to make a 3-level collapsing menu in Bootstrap? how to set active class to nav menu from twitter bootstrap How to make jQuery UI nav menu horizontal? Twitter Bootstrap add active class to li Adding a right click menu to an item

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation