1

I am trying to have my bootstrap site dynamically apply the active class to the current pages link.

Home | Questions | Login/Register | View | New

The questions page has multi pages within it so site.com/questions/index & site.com/questions/new for example. The link is for site.com/questions/index

I have my javscript adding the active class to the questions/index link but not to questions/new as I would like it to.

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 li').filter(function() {
    return this.href == url;
}).parent().addClass('active');

Have some Help?

Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81

1 Answers1

0

Please Run code snippet with Full Page and see the example.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
  <div id="navbar" class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a>
      </li>
      <li><a href="#about">About</a>
      </li>
      <li><a href="#contact">Contact</a>
      </li>
    </ul>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
  </script>
  <script>
       //Click on any li in ul with class 'navbar-nav'
      $('ul.navbar-nav li').click(function(e) {
        var $this = $(this); // declare variable for current li that we click
        $('ul.navbar-nav').find('li.active').last().removeClass('active') //find all li that class class active and remove
        $this.addClass('active'); //add 'active' class to current li.
      });
    </script>
</body>

</html>
Samda
  • 1,439
  • 12
  • 5