user1091508
user1091508

Reputation: 61

siblings issue - close all open panels when 1 is opened

IF i have this html:

<div class="main cat_info">
<h2>Question 1?</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
  <h2>question 2</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
  <h2>Question 3?</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
</div>

and I open one question, if another question is opened it closes (which is what I want). But when I wrap h2 and .answer in divs, it doesnt't work. Like:

<div class="main cat_info">
  <div class="holder">
<h2>Question 1?</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
</div>
<div class="holder">
  <h2>question 2</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
</div>
  <div class="holder">
  <h2>Question 3?</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
</div>
</div>

This is the jquery:

$(document).ready(function() {
$('.answer').hide();
$('.cat_info h2').on('click', function() {
    var state = $(this).next('.answer').is('.open');
    if (state) {
        $(this).removeClass('active').next('.answer').removeClass('open').fadeOut();
    }else{
        $(this).addClass('active').next('.answer').addClass('open').slideDown()
               .siblings('.answer').removeClass('open').slideUp().end()
               .siblings('h2').not(this).removeClass('active');
    }
    });
});

I guess it's siblings problem. Help?

Upvotes: 2

Views: 119

Answers (1)

adeneo
adeneo

Reputation: 318182

With that markup, it would probably look like :

$(document).ready(function() {
    $('.answer').hide();
    $('.cat_info h2').on('click', function() {
        var state = $(this).is('.active');
        if (state) {
            $(this).removeClass('active').next('.answer').fadeOut();
        } else {
            $(this).addClass('active').next('.answer').slideDown()
                   .closest('.holder').siblings('.holder').find('.answer').slideUp().end()
                   .find('h2').not(this).removeClass('active');
        }
    });
});​

FIDDLE

Upvotes: 4

Related Questions