user2041174
user2041174

Reputation: 51

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/

Upvotes: 3

Views: 181

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

Add an else block to the click event handler that closes the pane if it is not hidden.

$(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');
        }else{
            $('#accordion h2').removeClass('active').next().slideUp('slow');
        }
    });
});

JS Fiddle: http://jsfiddle.net/CzE3q/720/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337700

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

Upvotes: 3

Related Questions