patas1818 patas1818 - 6 months ago 40
Javascript Question

jquery toggle tabs hide active class when clicking same tab

when i click tab 1, 1 content show and active tab class is added.

when i click tab 2, 1 content hides remove tab active class and 2 content show and adds tab active class

but the effect i want is when i click tab 1, 1 content show, click again tab 1 content hides but the tab active class doesn't remove.

Any suggest will be help thanks

<div id="tabs_container">
<ul class="tabs">
<li>
<a href="#" rel="#tab_1_contents" class="tab">Option 1</a>
</li>
<li>
<a href="#" rel="#tab_2_contents" class="tab">Option 2</a>
</li>
</ul>

<div class="tab_contents_container">
<div id="tab_1_contents" class="tab_content tab_contents_active">
Option 1 stuff
</div>

<div id="tab_2_contents" class="tab_content">'
Option 2 stuff</div>
</div>

</div>
</div>

<script>
$('.tab-content').hide();

$('.tab').click(function() {
var target = $(this.rel);
$('.tab-content').not(target).hide();
target.toggle();

$('#tabs_container > .nav-tabs > li.tabActive')
.removeClass('tabActive');

$(this).parent().addClass('tabActive');

$('#tabs_container > .tab_contents_container > div.tab_contents_active')
.removeClass('tab_contents_active');

$(this.rel).addClass('tab_contents_active');
});
</script>

Answer

you need to use .toggleClass();

$('#tabs_container > .nav-tabs > li.tabActive').not($(this).parent()).removeClass('tabActive');
$(this).parent().toggleClass('tabActive');

$('.tab').click(function() {
     var target = $(this.rel);

  $('#tabs_container li').not($(this).parent()).removeClass('tabActive');

  $(this).parent().toggleClass('tabActive');

  $('#tabs_container > .tab_contents_container > div').not($(target)).removeClass('tab_contents_active'); 
  $(target).toggleClass('tab_contents_active');
 }).eq(0).click();
.tabActive{
  background : #005eff;
  padding : 5px;
  
}
.tabActive > a{
  color :#fff;
}

.tab_content{
  display : none;
}

.tab_contents_active{
  display : block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs_container">
   <ul class="tabs">
     <li>
       <a href="#" rel="#tab_1_contents" class="tab">Option 1</a>
     </li>
     <li>
        <a href="#" rel="#tab_2_contents" class="tab">Option 2</a>
     </li>
    </ul>

    <div class="tab_contents_container">    
      <div id="tab_1_contents" class="tab_content">
         Option 1 stuff     
      </div>

      <div id="tab_2_contents" class="tab_content">
         Option 2 stuff
      </div>

     </div>
</div>

Comments