Search code examples
twitter-bootstrap-3bootstrap-accordion

Bootstrap Accordion: subcollapse should close on close of supercollapse


<div id="accordion">
    <a role="button" data-parent="#accordion" href="#supercollapse1"> ITEM1 </a>
    <div id="supercollapse1">
            <a role="button" data-toggle="collapse" href="#subcollapse1" onclick=updateContent()> SUBITEM1 </a>
            <div id="subcollapse1">
                CONTENT
            </div>
    </div>
    <a role="button" data-parent="#accordion" href="#superollapse2"> ITEM2 </a>
    <div id="supercollapse2">
            <a role="button" data-toggle="collapse" href="#subcollapse2" onclick=updateContent()> SUBITEM2 </a>
            <div id="subcollapse2">
                CONTENT
            </div>
    </div>
</div>

What happens When I open supercollapse1 and then subcollapse1 and then supercollapse2, supercollapse1 closes together with subcollapse1 and supercollapse2 opens. Then I open supercollapse1 - supercollapse2 closes and supercollapse1 together with subcollapse1 opens.

What I want to achieve When supercollapse1 and subcollapse1 are open and I open supercollapse2, supercollapse1 closes together with subcollapse1, so that subcollapse1 does not show when supercollapse1 is opened again.

Motive All subcollapses share one content item which is generated each time they open. So when I already opened subcollapse1, then open subcollapse2 and go back to subcollapse1 - it is already open and content does not get generated.

Tried to be as clear as possible. No offense for the pseudocodish example.

Cheers


Solution

  • If I got you right, closing the level1 accordion(s) should close the level2 accordion(s) that are inside of the level1 accordion(s)

    Check out this fiddle: https://jsfiddle.net/459nzh32/

    The trick is to listen for the hide event of a level1 accordion, then find its children and close them too, here is an example with jquery:

    $('.level1').on('hidden.bs.collapse', function () {
      $(this).find('.level2').collapse('hide');
    });