Skip to content Skip to sidebar Skip to footer

Bootstrap Collapse - How To Add Additional Click Behavior That Depends On The State Of Collapse Or Not

I have a button that controls the expansion/collapse of a collapsible div. But I want to add additional functionality on click that depends on whether the div is expanding or coll

Solution 1:

The best thing you can do is read Bootstrap documentation :)

Your solution is not the best, because if you double click on your button fast enough it will execute code inside your if statement AND in else statement (with collapsing only once)

This event fires immediately when the show instance method is called.

$('#myCollapsible').on('show.bs.collapse', function () {
  // do something…
});

This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).

$('#myCollapsible').on('shown.bs.collapse', function () {
  // do something…
});

This event is fired immediately when the hide method has been called.

$('#myCollapsible').on('hide.bs.collapse', function () {
  // do something…
});

This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).

$('#myCollapsible').on('hidden.bs.collapse', function () {
  // do something…
});

Example:

$('[data-toggle="collapse"]').click(function() {
  var collapsibleDiv = $(this).closest('.panel').find('.panel-collapse');
  collapsibleDiv.on('show.bs.collapse', function() {
    $('body').css('background', '#1abc9c');
  });
  collapsibleDiv.on('shown.bs.collapse', function() {
    $('body').css('background', '#e74c3c');
  });
  collapsibleDiv.on('hide.bs.collapse', function() {
    $('body').css('background', '#3498db');
  });
  collapsibleDiv.on('hidden.bs.collapse', function() {
    $('body').css('background', '#7f8c8d');
  });
});

CODEPEN

Solution 2:

Your solution is the best for simple tasks that occur more frequently.

In addition to the collapsed class, you can use a special attribute:

Be sure to add aria-expanded to the control element. <...> The plugin will automatically toggle this attribute based on whether or not the collapsible element has been opened or closed.

Both of these methods indicate the status of the toggle button, but not the state of the object which is operated by the button. When an object is controlled by a few buttons, you need to look for other signs.

You can use three other classes to check the status of the object itself:

The collapse plugin utilizes a few classes to handle the heavy lifting: .collapse hides the content .collapse.in shows the content .collapsing is added when the transition starts, and removed when it finishes

Post a Comment for "Bootstrap Collapse - How To Add Additional Click Behavior That Depends On The State Of Collapse Or Not"