Reputation: 149
Hi I currently have the following setup - https://jsfiddle.net/scwbqffo/ Clicking on either tab would display content and switch between tabs (Not sure why it's not working in the fiddle but works fine on my site).
I'd like to be able to click on the tab again to close it if possible?
$(document).ready(function(){
$("ul#tabs li").click(function(e){
if (!$(this).hasClass("active")) {
var tabNum = $(this).index();
var nthChild = tabNum+1;
$("ul#tabs li.active").removeClass("active");
$(this).addClass("active");
$("ul#tab li.active").removeClass("active");
$("ul#tab li:nth-child("+nthChild+")").addClass("active");
}
});
});
<ul id="tabs">
<li>Show tab 1</li>
<li>Show tab 2</li>
</ul>
<ul id="tab">
<li>showing tab 1 content</li>
<li>showing tab 2 content</li>
</ul>
ul#tabs {
list-style-type: none;
padding: 0;
text-align: center;
}
ul#tabs li {
display: inline-block;
background-color: #252525;
border-bottom: solid 2px grey;
padding: 10px 20px;
margin-bottom: 4px;
color: #fff;
cursor: pointer;
}
ul#tabs li:hover {
background-color: grey;
}
ul#tabs li.active {
background-color: #00aeef;
}
ul#tab {
list-style-type: none;
margin: 0;
padding: 0;
}
ul#tab li {
display: none;
}
ul#tab li.active {
display: block;
}
Upvotes: 1
Views: 1265
Reputation: 10746
Add an else
in your jquery that removes the active
class
else {
$(this).removeClass('active');
$("ul#tab li.active").removeClass("active");
}
Upvotes: 1
Reputation: 731
You are missing jQuery in the jsFiddle, to answer your question you just need to use toggleClass
Upvotes: 0