Rob Morris
Rob Morris

Reputation: 533

Accordion toggle open/close

Sorry if this has been asked numerious times but I have an accordion which works, but I need it to toggle the currently open element. As it stands it dosen't close the currently opened element.

See my codepen

The Javasscript:

function accordion() {
    var allPanels = $('.accordion > dd').hide();

    $('.accordion > dt > a').on('click', function(e) {
        e.preventDefault();

        allPanels.slideUp(100);
        $(this).parent().next().slideDown(100);
        return false;
    });
}

accordion();

Upvotes: 1

Views: 920

Answers (2)

Batu.Khan
Batu.Khan

Reputation: 3065

You can do this

$(this).parent().next().slideToggle(100);      
allPanels.not($(this).parent().next()).slideUp(100);

DEMO

Upvotes: 0

laaposto
laaposto

Reputation: 12213

You should check if the tab is already open. If it is open and you click the title then slideUp. If it is not then slideDown as you already doing.

To check if an element is visible or not you can use .is(":visible")

You can use:

 if($(this).parent().next().is(":visible") ){

            $(this).parent().next().slideUp(100);
    }
    else{
            $(this).parent().next().slideDown(100);
    }

DEMO

Upvotes: 1

Related Questions