Javascript collapse div with JQuery and Bootstrap

Categories: 

Tags: 

Collapse only one div

HTML

<!-- user should click here -->
<button class="btn btn-collapse-toggle" type="button" data-toggle="collapse" data-target="target-div" title="Collapse">
        <i class="fa fa-lg fa-compress"></i>
</button>
 
<!-- "collapse in" start expanded, "collapse" start collapsed -->
<div id="target-div" class="collapse in"> Some content to be collapsed </div>

Javascript

$('.btn-collapse-toggle').on('click', function () {
    var ico = $(this).find('i');
    var target = $(this).attr('data-target');
 
    if (ico.hasClass('fa-expand')) {
        ico.removeClass('fa-expand');
        ico.addClass('fa-compress');
        $(this).attr('title','Minimize');
    } else {
        ico.removeClass('fa-compress');
        ico.addClass('fa-expand');
        $(this).attr('title','Maximize');
    }
 
    // here comes the effect
    $(target).collapse('toggle');
});

Collapse all div with the same class

HTML

<!-- user should click here -->
<button class="btn btn-collapse-toggle-all" type="button" data-toggle="collapse" data-target="target-div" title="Collapse All">
        <i class="fa fa-lg fa-compress"></i>
</button>
 
<!-- "collapse in" start expanded, "collapse" start collapsed -->
<div class="collapsible collapse in"> Some content to be collapsed 1 </div>
<div class="collapsible collapse in"> Some content to be collapsed 2 </div>
<div class="collapsible collapse in"> Some content to be collapsed 3 </div>

Javascript

$('.btn-collapse-toggle-all').on('click', function () {
    var ico = $(this).find('i');
 
    if (ico.hasClass('fa-expand')) {
        ico.removeClass('fa-expand');
        ico.addClass('fa-compress');
        $(this).attr('title','Minimize All');
    } else {
        ico.removeClass('fa-compress');
        ico.addClass('fa-expand');
        $(this).attr('title','Maximize All');
    }
 
    // here comes the effect
    $('.collapsible').collapse('toggle');
});