Currently in Bootstrap 3, when you are navigating panes using Bootstrap's tabs the "active" class is placed on the <li>
element like so:
<ul class="nav navbar-nav">
<li class="active"><a href="#A" data-toggle="tab">A</a></li>
<li><a href="#B" data-toggle="tab">B</a></li>
<li><a href="#C" data-toggle="tab">C</a></li>
</ul>
Instead, I am trying to get the "active" class to go on the <a>
element, like so:
<ul class="nav navbar-nav">
<li><a class="active" href="#A" data-toggle="tab">A</a></li>
<li><a href="#B" data-toggle="tab">B</a></li>
<li><a href="#C" data-toggle="tab">C</a></li>
</ul>
I was able to add the "active" class using the Bootstrap JavaScript events to the <a>
element using the below code, however I was not able to remove it from previously "active" elements, nor does it stop the "active" class from still changing on the <li>
elements. Is there a simple and lightweight solution to move the default behavior from the <li>
to the child <a>
element?
$('a[data-toggle="tab"]').on('show.bs.tab', function(event) {
$(event.target).addClass('active');
});
On the contrary to @Mina Ragaie comment it's important to take care of question content:
Instead, I am trying to get the "active" class to go on the element,
By default the active class follows the clicked li, but if you want to add another active class on the child anchor tag you need to change the event from 'show.bs.tab' to 'shown.bs.tab'. Add the row:
$(this).closest('.nav').find('.active').removeClass('active');
in order to remove any active added class.
In the following snippet an evidence:
$('a[data-toggle="tab"]').on('shown.bs.tab', function(event) {
$(this).closest('.nav').find('.active').removeClass('active');
$(event.target).addClass('active');
}).first().trigger('shown.bs.tab');
a.active {
background-color: blue !important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<ul class="nav navbar-nav">
<li class="active"><a href="#A" data-toggle="tab">A</a></li>
<li><a href="#B" data-toggle="tab">B</a></li>
<li><a href="#C" data-toggle="tab">C</a></li>
</ul>