Sqnkov Sqnkov - 1 month ago 26
Javascript Question

Simple jQuery accordion toggle

I am working on a simple accordion with toggle states using jQuery. So far so good, but when I click on a different toggle than the initial one that I've clicked on at the start it toggles itself, leaving the previous one with the opened state.

How can one do some kind of a check-up to see if there is another one opened and toggle its state as well?

Here is a Fiddle. Just mess around with it for a few seconds and you will understand what I mean.

// Accordion init
// Hide accordion content on load
$('.accordion-content').hide();
$('.widget-accordion').find('.accordion-toggle').click(function() {

// State change visuals
$(this).toggleClass('opened');

//Expand or collapse this panel
$(this).next().slideToggle('fast');

//Hide the other panels
$(".accordion-content").not($(this).next()).slideUp('fast');

});

Answer

As stated in my comment above, here a working fiddle.

The problem is that when you open one accordion item there is no other opened allowed which means that you have to clear every class which stands for the status open...

Working Fiddle

// Accordion init
// Hide accordion content on load
 $('.accordion-content').hide();
 $('.widget-accordion').find('.accordion-toggle').click(function() {
   $('.accordion-toggle').each(function(){
   $(this).removeClass("opened");
 });
 // State change visuals
 $(this).toggleClass('opened');

 //Expand or collapse this panel
 $(this).next().slideToggle('fast');

 //Hide the other panels
 $(".accordion-content").not($(this).next()).slideUp('fast');

});