Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close active accordion item

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/

like image 808
user2041174 Avatar asked Dec 02 '25 12:12

user2041174


1 Answers

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

like image 190
Rory McCrossan Avatar answered Dec 05 '25 01:12

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!