I found this sweet accordion menu and I want to modify it a little bit. I want to add a close function, so if I click on the h2 that's active it will slide up and close. How can I achieve that?
$(function() {
$('#accordion .content').hide();
$('#accordion h2:first').addClass('active').next().slideDown('slow');
$('#accordion h2').click(function() {
if ($(this).next().is(':hidden')) {
$('#accordion h2').removeClass('active').next().slideUp('slow');
$(this).toggleClass('active').next().slideDown('slow');
}
});
});
http://jsfiddle.net/tovic/CzE3q/
You need to check to see if the item you clicked on already has the active class. Try this:
$('#accordion .content').hide();
$('#accordion h2:first').addClass('active').next().slideDown('slow');
$('#accordion h2').click(function () {
var openPanel = !$(this).hasClass('active')
$('#accordion h2').removeClass('active').next().slideUp('slow');
openPanel && $(this).toggleClass('active').next().slideDown('slow');
});
Example fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With