Expand All & Collapse All Buttons using Bootstrap Collapse

Kynan Pacheco picture Kynan Pacheco · Jun 27, 2017 · Viewed 9.1k times · Source

I have a a few (8) collapsible fields using bootstrap that follow this:

        <div id='toggle'>
            <button type='button' data-toggle='collapse' data-target='#target' id='toggle'>Title</button>
        </div>
        <div id='target' class='collapse'>
            <p class='stuff'>Some Stuff Here</p>
        </div>

This works fine, but I want to have expand all and collapse all buttons. I figured that by adding two other buttons that call functions during the onClick event, then I could make them expand and collapse. I did this using:

<button type="button" onclick="expand()">Expand All</button>
<button type="button" onclick="collapse()">Collapse All</button>

That call these functions:

function expand() {
    $('.stuff').slideDown(400);
    $('.collapse').slideDown(400);
}

function collapse() {
    $('.stuff').slideUp(400);
    $('.collapse').slideUp(400);
}

These are half functional. The problem is that once the expand all and collapse all buttons are used the bootstrap buttons no longer not respond. Clicking collapse all makes the toggle only collapse, and clicking expand all makes the toggle only expand.

Is there a better way to do this, or a way to make my solution functional?

Answer

Kynan Pacheco picture Kynan Pacheco · Jun 27, 2017

Did some research on [Bootstrap via W3][1] and found that I could change my js/jquery functions to:

function expand() {
   $('.collapse').collapse('show');
}
function collapse() {
   $('.collapse').collapse('hide');
}

Bootstrap has the .collapse() method that could be used and solved the functionality issues. Thanks for the Responses!
[1]: https://www.w3schools.com/bootstrap/bootstrap_ref_js_collapse.asp