Umeed Umeed - 3 months ago 4
Javascript Question

How to toggle accordion using Javascript/jquery

I'm trying to get my accordion to toggle but nothing seems to be happening. By toggle I mean clicking the same accordion header should close it as well. So far I've managed to get it to work by clicking another header the previous one will close, but closing an open one and keeping them all closed seems to not be working.

here is my script:

$(document).ready(function() {
$("#accordion section h1").click(function(e) {


I've tried playing the collapse outside of the function
$(#accordion).collapse('toggle'), I've tried to use
('hide')` as well but no luck.

here is a jsfiddle of it: Jsfiddle

Any suggestions would be greatly appreciated!



Try this

$("#accordion section h1").click(function(e) {
  if (!$(this).closest('section').hasClass('ac_hidden')) {
  } else {

I've changed .parents() to .closest() as it's a better selector for this scenario, it will grab the closest section to the clicked header which is what we want, I've then just added a check to make sure the current element doesn't have the ac_hidden class and if not then add it (slide the current one up) else we are sliding a different one down and the functionality is what you pretty much had already. Hope that helps.