Search code examples
jqueryjquery-mobile

Accordion collapse/expand all in JQuery Mobile


I'm working with JQuery Mobile and I have a bunch of accordions on my page. I want to expand/collapse all the accordions at once, at the click of a button. How can this be done?


Solution

  • Does something like this work?

    JS

    $('#openAll').on('click', function() {
        $('.openMe').each(function() {
            var coll = $(this);
            coll.trigger('expand');
        });
    });
    $('#closeAll').on('click', function() {
        $('.openMe').each(function() {
            var coll = $(this);
            coll.trigger('collapse'); 
        });
    });
    

    Alternate JS ( without the foreach ):

    $('#openAll').on('click', function() {
        $('.openMe').trigger('expand');
    });
    $('#closeAll').on('click', function() {
        $('.openMe').trigger('collapse');
    });
    

    HTML

    <div data-role="collapsible" class="openMe">
       <h3>Hello 1</h3>
       <p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
    </div>
    <div data-role="collapsible" class="openMe">
       <h3>Hello 2</h3>
       <p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
    </div>
    <div data-role="collapsible" class="openMe">
       <h3>Hello 3</h3>
       <p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
    </div>
    <br />
    <a href="#" data-role="button" id="openAll">Open All Collapsible</a>
    <a href="#" data-role="button" id="closeAll">Close All Collapsible</a>
    ​
    

    Docs:

    Looks like this wont work on a set as only one can be open at a time:

    Set Docs: