Reputation: 8982
Attempting to create an accordion, but I can't figure out to check if the wrapper has the active class.
My jQuery:
$('.faq_wrap span.plus').on(touchClick, function (e) {
var topEl = $(this).closest('.faq_wrap');
if (topEl.hasClass('active')) {
topEl.removeClass('active');
topEl.find('.answer').slideUp('fast');
return false;
}
topEl.each(function (index, el) {
topEl.removeClass('active');
topEl.find('.answer').slideUp('fast');
});
topEl.find('.answer').slideDown('fast');
topEl.addClass('active');
console.log(topEl);
});
Here's the output from console.log
:
I'm trying to check whether .faq_wrap.active
already exists. If it does, slide the accordion up before sliding the new one down. As of right now, this check is ignored and I can open as many accordions at once as I want. Thoughts?
Upvotes: 0
Views: 123
Reputation: 10976
You have multiple collapsible/ expandable sections in your HTML, from which only one is ever going to be active (expanded). You use .closest()
but if there's only one you could just as well use the direct class selector .faq_wrap.active
(it will return either 0 or 1 element, depending on whether the user has already clicked). There's also no point in doing topEl.each
because .closest()
will return only the closest node (here, the parent). So the following should be better ( & more concise)
$('.faq_wrap span.plus').on(touchClick, function (e) {
var topEl = $(this).closest('.faq_wrap'),
activeEl = $('.faq_wrap.active');
if (activeEl.length) { // implied: if it's bigger than 0
activeEl.removeClass('active');
activeEl.find('.answer').slideUp('fast');
}
topEl.find('.answer').slideDown('fast');
topEl.addClass('active');
});
NB: Just wondering, why did you use the return false;
statement?
Upvotes: 0