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
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.
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();
});
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; }
if( !$(this).parents("section").hasClass("ac_hidden")){ $(this).parents().addClass("ac_hidden"); console.log(1) return; }
check this out: https://jsfiddle.net/jxyozw5c/3/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.