user6827401 user6827401 - 2 months ago 20
jQuery Question

bootstrap active nav tab not highlighting on click although the href link is working

Here is the code of the html.

<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active"><a href="div1">Home</a></li>
<li><a href="#div2">Inside</a></li>
<li><a href="#div3">Images</a></li>
<li><a href="#div4">Contact</a></li>
</ul>
</nav>
</div>


Here is the jquery code:

$(document).read(function(){
$(".nav li").on("click", function() {
$(".nav li").removeClass("active");
$(this).addClass("active");
});
})


How can I change it so that it highlights the tab I am clicking.

Answer

You have missed a nav tag in you code and also remove the collapse class from the navigation bar

HTML

 <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.7/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="navbar-collapse" id="myNavbar">
    <nav>
    <ul class="nav navbar-nav">
    <li class="active"><a  href="#">Home</a></li>
    <li><a  href="#">Inside</a></li>
    <li><a  href="#">Images</a></li> 
    <li><a  href="#">Contact</a></li> 
    </ul>
    </nav>
    </div>

JQUERY

$(document).ready(function(){
$(".nav li").on("click", function() {
  $(".nav li").removeClass("active");
  $(this).addClass("active");
});
   })

JSFIDDLE