views:

298

answers:

3
// ACCORDION
$('.accordion .answer').hide(); // hide all
$('.accordion .question').click(function(){
        $('.accordion .answer').slideUp(); // hide all open
        $(this).addClass('active').next().slideDown(); // show the anwser
        return false;
});

HTML:

<dl class="accordion">
    <dt class="question">question</dt>
    <dd class="answer">answer</dd>
    <dt class="question">question</dt>
    <dd class="answer">answer</dd>
</dl>

... works, but

  • the 'active' class must removed from inactive question elements and
  • atleast one of the answer remains open; all answers should be able to close.

Thanks!

+1  A: 
$('.accordion .answer').hide(); // hide all
$('.accordion .question').click(function(){
    if($(this).hasClass('active')) {
        $(this).removeClass('active').next().slideUp();
    } else {
        $('.accordion .answer').removeClass('active').slideUp();
        $(this).addClass('active').next().slideDown();
    }
    return false;
});

But you should really take a look at the jQuery UI Accordion.

tdolsen
Almost works! But 1) it allows opening multiple answers and 2) if you open first and then the second, both retain the 'active' class.
Nimbuz
You are absolutely right, a minor bug(forgot a dot(.)) and a flaw in my thinking(forgot to slide up inactives). Should work now, but I see you figured it out yourself. :)
tdolsen
+1  A: 

Okay, figured it:

$('.accordion .answer').hide(); // hide all
$(".accordion .question").click(function () {
    $(this).toggleClass('active').next(".answer").slideToggle(300).siblings(".answer").slideUp("slow");
    $(this).siblings().removeClass('active');
});
Nimbuz