virs90 virs90 - 3 months ago 14
HTML Question

Show and hide tab content on click

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;
}

Answer

Add an else in your jquery that removes the active class

else {
  $(this).removeClass('active');
  $("ul#tab li.active").removeClass("active");
}

jsfiddle