Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Try this

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

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.

jsFiddle

Solution 2:

This is the javascript code for the accordion on my website, benstechgarage.com/accordion.html

$('.accordion').on('click', '.accordion-control', function(e) {
      e.preventDefault();
      $(this)
        .next('.accordion-panel')
        .not(':animated')
        .slideToggle();
    });

Solution 3:

you just have to check if it have the class so you can close it if( !$(this).parents("section").hasClass("ac_hidden")){ $(this).parents().addClass("ac_hidden"); console.log(1) return; }

check this out: https://jsfiddle.net/jxyozw5c/3/

Post a Comment for "How To Toggle Accordion Using Javascript/jquery"