Bootstrap Collapse

This article will teach you how to use Bootstrap to display and hidden items.


Toggle Display of Content with Bootstrap

The Bootstrap collapse JavaScript plugin enables you to easily toggle the visibility of specific elements on a web page, allowing you to show and hide content as needed. Typically, buttons and anchors (i.e., <button> and <a> elements) serve as triggers that control the elements you want to toggle.

Expand and Collapse Elements via Data Attributes

You can achieve this functionality in Bootstrap by utilizing data attributes, without the need to write any JavaScript code. Let's explore an example to see how it works:

<!-- Trigger Buttons HTML -->
<p>
<a href="#myCollapse" data-bs-toggle="collapse">Toggle Element</a>
<button type="button" class="btn btn-primary ms-4" data-bs-toggle="collapse" data-bs-target="#myCollapse">Toggle Element</button>
</p>

<!-- Collapsible Element HTML -->
<div class="collapse show" id="myCollapse">
<div class="card card-body">Content to disply or hide.</div>
</div>

In the provided example, we have created a collapsible control without writing any JavaScript code. Let's break down each part of this code for better understanding:

Explanation of Code

The Bootstrap collapse plugin requires two essential elements to function properly: the trigger element (e.g., a button or hyperlink) and the collapsible element itself.

  • The data-bs-toggle=collapse attribute is added to the trigger element, along with a data-bs-target attribute (for buttons) or href attribute (for anchors) to specify which collapsible element the trigger controls.
  • The data-bs-target or href attribute accepts a CSS selector (e.g., id selector #myCollapse in our example) to identify the specific collapsible element.
  • The class .collapse is added to the collapsible element (line no-6) to indicate that it can be collapsed.
  • Optionally, you can include the class .show (line no-6) along with .collapse to make the collapsible element open by default.

Expand and Collapse Elements via JavaScript

You also have the option to expand and collapse elements manually using JavaScript by calling the collapse() Bootstrap method with the id or class selector of the collapsible element.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myCollapse").collapse("toggle");
    });
});
</script>

<!-- Trigger Buttons HTML -->
<p>
<button type="button" id="myBtn" class="btn btn-primary ms-4" data-bs-toggle="collapse" data-bs-target="#myCollapse">Toggle Element</button>
</p>

<!-- Collapsible Element HTML -->
<div class="collapse show" id="myCollapse">
<div class="card card-body">Content to disply or hide.</div>
</div>

Bootstrap Collapse Options

You can customize the functionality of a collapsible element by passing certain options to the collapse() Bootstrap method.

  • parent: Type: selector, Default: false

    When this collapsible items is invoked, all other collapsible components under the given parents will be closed.

  • toggle: Type: boolean, Default: true

    Toggles the collapsible element on invocation.


Bootstrap Collapse Methods

The typical approaches for bootstrap collapse are as follows:

Passing options: You have the option to pass additional configuration settings to the collapse by using an options object. In the following example, the collapsible element's display behavior will not toggle on invocation because the toggle option for the collapsible element is set to false.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myCollapse").collapse("toggle", {
            toggle: false
        });
    });
});
</script>

Toggle: A collapsible element is toggled (shown or hidden) using this way.

<script>
$(document).ready(function () {
    // Toggle collapse element on button click
    $("#toggleBtn").click(function () {
        $("#myCollapse").collapse("toggle");
    });
});
</script>

Show: This technique displays a collapsible element.

<script>          
$("#showBtn").click(function () {
    $("#myCollapse").collapse("show");
});
</script>

Hide: A collapsible element is hidden using this technique.

<script>
$("#hideBtn").click(function () {
    $("#myCollapse").collapse("hide");
});
</script>

Bootstrap Collapse Events

Few events are available in the Bootstrap collapse classes for hooking into the functionalities of collapse.

  • show.bs.collapse: When the display instances method is called, this event is instantly triggered.
  • shown.bs.collapse: A collapse element becomes visible to the users at the time this event is initiated. It won't allow itself be dismissed until the CSS transition is finished in its entirety.
  • hide.bs.collapse: As soon as the conceal method is invoked, this event is instantly triggered.
  • hidden.bs.collapse: This event is triggered whenever a collapse element is made inaccessible to the users. It won't be fired until after the CSS transition has been finished in its entirety.

The following example displays an alert message to the user when the sliding transition of a collapsible element has been fully completed.

<script>
$(document).ready(function () {
    $("#myCollapse").on("hidden.bs.collapse", function () {
        alert("Collapsible element has been completely closed.");
    });
});
</script>

FAQ

What is Bootstrap Collapse?

Bootstrap Collapse is a JavaScript component that allows you to create collapsible content sections on a web page. It provides a way to hide or show content with a smooth transition, enhancing the user experience by allowing them to focus on the information they're interested in while minimizing clutter.

What are some customization options for Bootstrap Collapse?

Bootstrap Collapse provides various customization options to control its behavior and appearance:

  • Animation: You can customize the animation duration and easing using data attributes like data-toggle, data-target, and data-parent.
  • Events: Collapse components trigger events like show.bs.collapse and hide.bs.collapse, which you can use to execute custom JavaScript code when the collapse is shown or hidden.
  • Multiple Collapses: By using a data-parent attribute, you can group collapse elements so that opening one collapse will automatically close others within the same group.
  • Accordion: By combining multiple collapse elements with the same data-parent value, you can create an accordion-style interface where only one collapse can be open at a time.

Is Bootstrap Collapse responsive?

Yes, Bootstrap Collapse is responsive by default. Bootstrap is designed to create responsive and mobile-friendly websites, and Collapse components inherit this behavior. When you use Collapse within a Bootstrap layout, the collapsible content will adjust its size and visibility based on the screen width and device type.

How can I add an icon or indicator to show the collapse state?

You can add an icon or indicator to show the collapse state by incorporating a Font Awesome icon or a similar CSS icon library. Here's how you can do it:

<button class="btn btn-link" data-toggle="collapse" data-target="#collapseExample">
  Toggle Content
  <i class="fas fa-chevron-down"></i>
</button>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Collapsible content here.
  </div>
</div>

In this example, the Font Awesome icon class fa-chevron-down is added to the button element. You can replace it with other icon classes as needed. Remember to include the appropriate icon library and its styles in your HTML.

Can I control the initial state of a Bootstrap Collapse?

Yes, you can control the initial state of a Bootstrap Collapse component by adding the show class to the collapsible element you want to be open by default. Without the show class, the content will be hidden when the page loads.

<button class="btn btn-link" data-toggle="collapse" data-target="#defaultOpen">
  Toggle Default Open
</button>
<div class="collapse show" id="defaultOpen">
  <div class="card card-body">
    Default open content.
  </div>
</div>

In this example, the content inside the defaultOpen collapse is shown when the page loads because of the show class.

Can I customize the transition effect of Bootstrap Collapse?

Yes, you can customize the transition effect of Bootstrap Collapse using CSS. Bootstrap Collapse uses CSS transitions to create the opening and closing animations. You can override the default transition duration and easing function by targeting the collapse element and modifying the appropriate CSS properties. For instance, to make the transition slower and use a different easing function:

.collapse {
  transition: height 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55);
}

In this example, the transition duration is set to 0.5 seconds, and the cubic-bezier easing function is customized for a specific animation effect.

Can I use JavaScript to control Bootstrap Collapse programmatically?

Yes, you can control Bootstrap Collapse components programmatically using JavaScript. You can use the Bootstrap Collapse JavaScript methods to show or hide collapse elements. Here's an example:

// Show a collapse
$('#collapseElement').collapse('show');

// Hide a collapse
$('#collapseElement').collapse('hide');

// Toggle a collapse
$('#collapseElement').collapse('toggle');

In this example, replace #collapseElement with the appropriate selector for your collapse element. This is useful when you want to trigger collapse actions based on user interactions or events other than clicks.

How can I animate the transition of the Bootstrap Collapse height instead of using the default slide animation?

By default, Bootstrap Collapse uses a slide animation to transition the height of the collapsible element. If you want to customize the animation or use a different effect, you can override the default CSS transition and implement your own animation. For example, to use a fade-in effect:

.collapse {
  opacity: 0;
  max-height: 0;
  transition: opacity 0.3s ease, max-height 0.3s ease;
}

.collapse.show {
  opacity: 1;
  max-height: 1000px; /* Set to a value larger than the expected content */
}

In this example, the collapse animation uses opacity and max-height to create a fade-in effect instead of the default slide animation.

Is it possible to add custom animations to Bootstrap Collapse transitions?

Yes, you can add custom animations to Bootstrap Collapse transitions by utilizing CSS animations or transitions. You can create your own keyframes and apply them to the collapse element to achieve unique animations. Here's an example of a custom bounce animation:

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.collapse {
  animation: bounce 0.5s ease;
}

In this example, the collapse element will use the custom bounce animation during its transition.

Can I use Bootstrap Collapse without using jQuery?

Yes, you can use Bootstrap Collapse without jQuery by using Bootstrap's native JavaScript implementation, which is available in newer versions of Bootstrap (starting from Bootstrap 4). Instead of relying on jQuery, you can use the data-bs-toggle and data-bs-target attributes along with Bootstrap's own JavaScript library for toggling collapses.

Can I include images or media within a collapsed section?

Yes, you can certainly include images or media within a collapsed section. Bootstrap Collapse doesn't restrict the type of content you can place within the collapsed area. You can include images, videos, audio, or any other type of HTML content.

<button class="btn btn-link" data-toggle="collapse" data-target="#imageCollapse">
  Toggle Image
</button>
<div class="collapse" id="imageCollapse">
  <div class="card card-body">
    <img src="path-to-your-image.jpg" alt="Collapsed Image">
  </div>
</div>

How can I make a collapsible sidebar menu using Bootstrap Collapse?

To create a collapsible sidebar menu using Bootstrap Collapse, you can structure your HTML with a combination of navigation items and collapse components. Here's a simplified example:

<div class="sidebar">
  <nav class="nav flex-column">
    <a class="nav-link" data-toggle="collapse" href="#submenu1">Section 1</a>
    <div class="collapse" id="submenu1">
      <a class="nav-link" href="#">Subsection 1.1</a>
      <a class="nav-link" href="#">Subsection 1.2</a>
    </div>
    <a class="nav-link" data-toggle="collapse" href="#submenu2">Section 2</a>
    <div class="collapse" id="submenu2">
      <a class="nav-link" href="#">Subsection 2.1</a>
      <a class="nav-link" href="#">Subsection 2.2</a>
    </div>
  </nav>
</div>

In this example, clicking on the main section links toggles the visibility of subsections using Bootstrap Collapse.


Conclusion

Bootstrap Collapsible Elements offer a versatile and user-friendly solution for managing content visibility within web interfaces. The framework's commitment to responsive design is evident in its Expandable Sections and Dynamic Content Collapse, providing an optimal user experience across various devices.

The flexibility of Collapsible Panel Design allows developers to create interactive and organized layouts, enhancing the overall structure of web content. With the ability to Hide and Show Elements and the implementation of Expand and Collapse Functionality, Bootstrap enables the creation of intuitive interfaces that adapt to user interactions.

The inclusion of Toggleable Sections and Animated Collapse Transitions adds a layer of sophistication to the user experience, ensuring smooth and visually appealing content transitions. Sectional Hiding further refines content organization, allowing users to focus on relevant information while concealing non-essential elements.

The feature-rich Bootstrap framework facilitates the creation of elements that are not only toggleable but also offer Collapse with Smooth Transitions, contributing to a seamless and polished interface.