Reputation: 53
Im after some advice on the use of jquery and bootstrap if anyone can assist.
I have the following HTML
<ul class="nav nav-pills nav-fill">
<li class="nav-item">
<a class="nav-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">Our Services</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">Our Venues</a>
</li>
</ul>
I then have the following jquery
$('ul.nav li a').click(function (e) {
$('ul.nav li.active').removeClass('active')
$(this).parent('li').addClass('active')
})
Now what i want to create is an active state when the nav-link is clicked and it to move to whatever tab is being selected, which this does but what it doesnt do is remove the active if you select a link to open and the select the same to close?
Could anyone assist with this please?
Upvotes: -1
Views: 5266
Reputation: 53
Thanks to both responses, both have achieved the result i'm after and I thank you both for the information and the detailed responses, this helps me to understand why I wasn't achieving the desired result.
Upvotes: 0
Reputation: 4335
If you want to add and remove the class with the same click
event (on first click add the class, then the next removes the class), you could use toggleClass
to achieve it:
$('ul.nav li a').click(function (e) {
// Select the parent li
var el = $(this).parent();
// Remove the class to the other li.active elements
$('ul.nav li.active').not(el).removeClass('active');
// Toggle the class to the current element: add the class if not present, removes the class if present
el.toggleClass('active');
});
More info about toggleClass at the jQuery website.
Hope it helps!
Upvotes: 2
Reputation: 187
The core issue is that you're first removing the class and then adding the class. If you already have the class and then add and remove it, of course it will still be there. So in order for you to remove the class if it already exsists you'll have to write a conditional statement like so:
$(document).ready(function(){
$('ul.nav li a').click(function (e) {
if($(this).parent('li').hasClass('active')){
$('ul.nav li.active').removeClass('active')
}
else {
$('ul.nav li.active').removeClass('active')
$(this).parent('li').addClass('active')
}
})
});
or you can use jQuery's toggle class
Upvotes: 0