SorryEh
SorryEh

Reputation: 928

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) {
    $(this).parents().siblings("section").addClass("ac_hidden");
    $(this).parents("section").removeClass("ac_hidden");
    $(this).collapse('toggle')
    e.preventDefault();
  });

});

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!

Thanks

Upvotes: 0

Views: 3332

Answers (3)

Anas Omar
Anas Omar

Reputation: 504

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/

Upvotes: 1

Ben's Tech Garage
Ben's Tech Garage

Reputation: 11

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();
    });

Upvotes: 1

Mark Walters
Mark Walters

Reputation: 12390

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

Upvotes: 3

Related Questions