Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle divs correctly

I have a section with questions and answers where I want only one question to be open at a time. So if you have 1 question open (answer is visible) then other answers will be closed. I can't find a way to close the open div itself.

Example (clarification): If you click Question1, Answer1 shows. If you click Question1 again Answer1 doesn't hide (and it should). Only 1 Answer should be shown at a time. Class 'active' has to be applied only to the open question and removed from prevously open ones.

Here is a demo of what I've done so far:

$('.tab-body').hide();

$('.tab-head').click(function () {

$('.tab-body').hide();
$(this).parents('.tab-faq').find('.tab-body').slideToggle();

$('.tab-head').removeClass('active');
$(this).addClass('active');

});
like image 416
Mariyan Avatar asked Dec 10 '25 09:12

Mariyan


2 Answers

You can do:

$('.tab-body').hide();
$('.tab-head').click(function () {
    var tabBody = $(this).next();
    tabBody.slideToggle();
    $('.tab-body').not(tabBody).slideUp();
    $('.tab-head').removeClass('active');
    $(this).addClass('active');
});

Updated Fiddle

like image 193
Felix Avatar answered Dec 11 '25 21:12

Felix


$('.tab-body').hide();

$('.tab-head').click(function () {
    if ($(this).hasClass('active')) {

        $(this).parents('.tab-faq').find('.tab-body').slideToggle();
        $('.tab-head').removeClass('active');
    } else {
        $('.tab-body').hide();
        $(this).parents('.tab-faq').find('.tab-body').slideToggle();

        $('.tab-head').removeClass('active');
        $(this).addClass('active');
    }
});

the hide in the click is not needed;

*edit rest of the divs will slide down

like image 27
Shikiju Avatar answered Dec 11 '25 22:12

Shikiju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!