Reputation: 9939
I have a page where there are questions with answers hidden underneath them. When someone clicks on a question, the answer slides down (this is a seperate function which works fine). When clicked again, it returns to its hidden state.
The problem I am having is a seperate link #expand-close a
that when clicked, will open/close ALL the answers to the questions.
When an answer is already open, this function runs and opens all the closed answers but closes all the open answers.
I want it to open all and keep the open answers open, and close all and keep the closed answers closed.
$('#expand-close a').click(function () {
$(this).toggleClass("hide");
$('.faq-hideable').slideToggle(500);
$('.faq-hideable').closest('li').find('h2').toggleClass('p-open');
});
Upvotes: 2
Views: 1366
Reputation: 86844
For the adding/removing classes, this is simple since toggleClass()
has an optional switch
parameter which determines if the class should be added or removed (instead of simply toggling it).
There's no such facility for .slideToggle()
so we do this manually using an basic if/else clause to choose between a slideUp()
or slideDown()
.
$('#expand-close a').click(function () {
var tohide = $(this).toggleClass("hide").hasClass("hide");
if (tohide) {
$('.faq-hideable').slideUp(500);
} else {
$('.faq-hideable').slideDown(500);
}
$('.faq-hideable').closest('li').find('h2').toggleClass('p-open', !tohide);
});
If you want something more succinct (but less readable):
$('#expand-close a').click(function () {
var tohide = $(this).toggleClass("hide").hasClass("hide");
$('.faq-hideable')[tohide ? "slideUp" : "slideDown"](500)
.closest('li').find('h2').toggleClass('p-open', !tohide);
});
Upvotes: 1
Reputation: 13825
I have something like your open/close system I use a if
close like this:
$('#expand-close a').click(function () {
if ($('.faq-hideable').is(':hidden')) {
$('.faq-hideable').show();
}
else {
$('.faq-hideable').hide();
}
});
Hope it can help you
Upvotes: 0
Reputation: 4886
try something like the following (you will need to change the selector to match your html/clases):
$('#expand-close a').click(function () {
$(this).toggleClass("hide");
if($(this).hasClass("hide")){
$('.faq-hideable .answer:visible').slideToggle(500);
}else{
$('.faq-hideable .answer:hidden').slideToggle(500);
}
$('.faq-hideable').closest('li').find('h2').toggleClass('p-open');
});
Upvotes: 0