Johnny Kermode
Johnny Kermode

Reputation: 75

jQuery Toggle: Close all other tabs when 1 is active

I'm trying to find a solution for this one, but I have not found a way to fix it yet. I would like to close all other tabs when one tab is active.

/* ------------------------------------------------------------------------ */
/* Toggle
/* ------------------------------------------------------------------------ */
if( $(".toggle .toggle-title").hasClass('active') ){
    $(".toggle .toggle-title.active").closest('.toggle').find('.toggle-inner').show();
}

$(".toggle .toggle-title").click(function(){
    if( $(this).hasClass('active') ){
        $(this).removeClass("active").closest('.toggle').find('.toggle-inner').slideUp(200,'easeOutQuad');
    }
    else{
        $(this).addClass("active").closest('.toggle').find('.toggle-inner').slideDown(200,'easeOutQuad');
    }
});

HTML:

<div class="toggle">
    <div class="toggle-title">
    <i class="fa fa-plus"></i>HEADLINE OF TOGGLE</div>
    <div class="toggle-inner" style="display: none;">
        <p>Lorem ipsum text to show.</p>
    </div>
</div>

Any ideas how to fix this?

Upvotes: 1

Views: 986

Answers (1)

Pedram
Pedram

Reputation: 16615

Well, I prefer to re-write your code, here is the clean version of your code, now if you want to:

Close all other tabs when 1 is active

Just close all, before open this:

$('.toggle-inner').slideUp(200);

$(".toggle-title").click(function() {
  if ($(this).hasClass('active')) {
    $(this).removeClass('active');
    $(this).siblings('.toggle-inner').slideUp(200);
  } else {   
    $('.toggle-inner').slideUp(200);
    $('.toggle-title').removeClass('active');
    
    /* or use not()
    $('.toggle-inner').not($(this).siblings()).slideUp(200);
    $('.toggle-title').not($(this)).removeClass('active');*/
    
    $(this).addClass('active');
    $(this).siblings('.toggle-inner').slideDown(200);   
  }
});
.active {
  background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggle">
  <div class="toggle-title">
    <i class="fa fa-plus"></i>HEADLINE OF TOGGLE</div>
  <div class="toggle-inner" style="display: none;">
    <p>Lorem ipsum text to show.</p>
  </div>
</div>

<div class="toggle">
  <div class="toggle-title">
    <i class="fa fa-plus"></i>HEADLINE OF TOGGLE</div>
  <div class="toggle-inner" style="display: none;">
    <p>Lorem ipsum text to show.</p>
  </div>
</div>

<div class="toggle">
  <div class="toggle-title">
    <i class="fa fa-plus"></i>HEADLINE OF TOGGLE</div>
  <div class="toggle-inner" style="display: none;">
    <p>Lorem ipsum text to show.</p>
  </div>
</div>

Upvotes: 1

Related Questions