grimlok grimlok - 2 months ago 6
HTML Question

jquery [tabs] open and close

this is my first question on Stack Overflow.
Need some help with tabs. Now when i click one of h3 tags i open tab content, but i wanna close it on next click in h3.

Apologize for my bad english skills, hope you all understand what i meant.

this is my html:

<div class="sub-aside">
<h3 class="sub-category" data-tab="tab-1">shopping communities</h3>
<ul class="first-side-menu drop-content sub-content" id="tab-1">
<li><a href="#">Home Goods</a></li>
<li><a href="#">Cooking</a></li>
</ul>
</div>
<div class="sub-aside">
<h3 class="sub-category" data-tab="tab-2">life events</h3>
<ul class="drop-content sub-content" id="tab-2">
<li><a href="#">Anniversary</a></li>
<li><a href="#">Back to school</a></li>
</ul>
</div>


and my jquery code:

$(".sub-category").on('click', function () {
var tab_id = $(this).attr('data-tab');

$('.sub-category').removeClass('content-active');
$('.sub-content').removeClass('content-active');

$(this).addClass('content-active');
$("#"+tab_id).addClass('content-active');

$('.sub-category').toggleClass('content-active');
})

Answer

You can use toggle.

$(".sub-category").on('click', function () {
 $(this).next('ul').toggle();       
})

$(".sub-category").on('click', function () {
 //Toggle particular element 
 $(this).next('ul').toggle();      
 //Hide all the elements not the clicked one  
 $(".sub-category").next('ul').not($(this).next('ul')).hide(); 
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sub-aside">
                <h3 class="sub-category" data-tab="tab-1">shopping communities</h3>
                <ul class="first-side-menu drop-content sub-content" id="tab-1">
                    <li><a href="#">Home Goods</a></li>
                    <li><a href="#">Cooking</a></li>
                </ul>
            </div>
            <div class="sub-aside">
                <h3 class="sub-category"  data-tab="tab-2">life events</h3>
                <ul class="drop-content sub-content" id="tab-2">
                    <li><a href="#">Anniversary</a></li>
                    <li><a href="#">Back to school</a></li>
                </ul>
            </div>