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');
});
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
$('.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With