there are a 4 accordions on the page, currently the open accordion only closes when you click on another accordion. I need to also close when you click on it. Here's the code I used.
$(document).ready(function() {
var accordionEntries = document.querySelectorAll('.accordion-entry');
var accordionImages = document.querySelectorAll('.accordion-image');
for (var i = 0; i < accordionEntries.length; i ) {
accordionEntries[i].dataset.target = 'accordion-image-' i;
accordionImages[i].classList.add('accordion-image-' i);
}
$(document).on('click', '.accordion-header', function() {
$('.accordion-open').removeClass('accordion-open')
var parent = $(this).closest('.accordion-entry');
parent.addClass('accordion-open');
$('.' parent.data('target')).addClass('accordion-open')
})
})
CodePudding user response:
The issue is caused by:
$('.accordion-open').removeClass('accordion-open')
which closes all accordion panels including the one you click on, then (re)opens the current one.
If you want to "toggle" the accordion panel, you need to check if the current panel is open first, then close it, then do nothing.
This can be achieved with:
$(document).on('click', '.accordion-header', function() {
if ($(this).is(".accordion-open")) {
$(this).removeClass("accordion-open");
return;
}
...