Close accordions if other accordian is open in jquery

前端 未结 1 701
野性不改
野性不改 2020-12-07 01:46

I have multiple jquery accordions on one page all with different id\'s etc.. I\'m attempting to only allow one accordion to open at a time. For example the user opens one an

相关标签:
1条回答
  • 2020-12-07 02:30

    Assuming you are using the jQuery UI accordion, you can collapse all sections with .accordion('activate', false).

    First, in your HTML, give all accordion containers class="accordion" to make them more readily addressable as a group. You can keep the id="accordion1" etc. attributes if you need to address the accordions individually.

    Then, initialize the accordions in a single $(function(){...}) structure (just once, not 3 times), as follows :

    $(function() {
        var activeAccordian = null;
        var $accordions = $(".accordion").on('click', function() {
            activeAccordian = this;
        }).accordion({
            collapsible: true,
            active: false,
            icons: false
        }).on('accordionchange', function(event, ui) {
            $accordions.not(activeAccordian).accordion('activate', false);
        });
    });
    

    DEMO

    Tracking the active accordion with activeAccordian is all important as it allows reciprocal re-closure of the freshly opened accordion to be suppressed.

    EDIT:

    The "aussi la solution" below, in which .on('accordionchange' ...) is replaced with .on('click' ...) makes me realise that the whole thing will simplify to :

    $(function() {
        var $accordions = $(".accordion").accordion({
            collapsible: true,
            active: false,
            icons: false
        }).on('click', function() {
            $accordions.not(this).accordion('activate', false);
        });
    });
    

    The need to track the active accordion disappears as .not(this) in the click handler suffices.

    DEMO

    0 讨论(0)
提交回复
热议问题