Set active to bootstrap nav class

I've a bootstrap navbar and i want to set active class for another li element when i click on it.

HTML

<nav class="navbar">
  <div class="navbar-default" >
    <ul class="nav navbar-nav">
      <li class="active"><a>Content</a></li>
      <li><a>News</a></li>
      <li><a>Subject</a></li>
    </ul>
  </div>
</nav>

CSS

<script type="text/javascript">
  $('.navbar-nav li').click(function() {
    $('.navbar li').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
  });
</script>

Not working, i'm new in javascript. I think i might be declaring the class element wrong and jQuery doesnt recongnize my script.

Answers 1

  • It works with data-toggle="tab" activate a tab without javascript.

    <nav class="navbar">
      <div class="navbar-default" >
        <ul class="nav navbar-nav">
          <li class="active"><a data-toggle="tab">Content</a></li>
          <li><a data-toggle="tab">News</a></li>
          <li><a data-toggle="tab">Subject</a></li>
        </ul>
      </div>
    </nav>
    

Related Articles