Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to use the Bootstrap Collapse Component

In today’s dynamic web development landscape, having clean and user-friendly interfaces is critical. Bootstrap, a popular front-end framework, provides an extensive number of components to make this process easier. Among them, the bootstrap collapse component stands out as an effective tool for controlling content visibility. Whether you’re a seasoned developer or new to web design, knowing how to correctly incorporate and adjust collapsible elements can significantly improve the user experience of your website.

This article offers a complete guide to the bootstrap collapse component, covering its fundamental workings and providing practical examples. We’ll look at Bootstrap Collapse’s adaptability, from creating accordion-style layouts to controlling content visibility using data attributes and JavaScript. By the end of this article, you will not only understand the physical concepts of this component, but also how to effectively integrate it into your websites. Let’s go on this adventure to understand the intricate workings of the Bootstrap Collapse component and improve your web design skills.


How it works

Bootstrap collapse

The bootstrap collapse component hides and reveals content on a web page with a smooth transition. This is especially handy for making collapsible menus, accordions, and hiding large blocks of text. The basic idea is to define a trigger element (such as a button or a link) and a target element (the material you want to hide or reveal). When the user pressed a trigger, the target element contracts or expands.

To achieve the collapsible behavior, it uses a combination of HTML, CSS, and JavaScript. Here’s a high-level explanation of how it works:

HTML structure

You define the structure of your collapsible content in HTML. This usually entails defining a trigger element (like a button or a link) and a target element (the content you want to conceal or reveal).
The trigger element is what the user interacts with to change the collapse state.

Data attributes

Bootstrap uses data attributes (such as data-toggle and data-target) to connect the trigger and target components. The data-toggle=”collapse” attribute indicates that the element acts as a trigger for a collapsible element, while data-target defines which element should collapse or expand.

JavaScript interaction

Bootstrap collapse provides JavaScript utilities for dynamically controlling the collapse behavior. For example, you can use the collapse(‘toggle’) function to dynamically change the visibility of the target element. JavaScript handles user activities, such as clicks on the trigger element, and updates the visible state of the target element accordingly. We’ll see this in action later.

Accessibility

Bootstrap incorporates accessibility features via ARIA properties. These characteristics aid modern screen readers in understanding and communicating state changes to users with disabilities.
For example, the aria-expanded attribute dynamically updates to indicate whether the collapsible element is expanded or collapsed.

CSS transition

Bootstrap uses CSS transitions to generate seamless animations throughout the collapse and expand processes. This provides a visually pleasing and smooth user experience. The .collapse class in Bootstrap’s CSS specifies how the transition between collapsed and expanded states should appear.

Customization

Bootstrap offers a variety of customization options, allowing us to tailor the default behavior to match specific design needs. We can utilize extra classes, styles, and JavaScript functions to create more complicated interactions, such as accordion-style layouts or toggling numerous items at the same time.

In essence, the bootstrap collapse component smoothly blends HTML, CSS, and JavaScript to create collapsible content. By combining these technologies and adhering to bootstrap principles, we can design a versatile and user-friendly solution for managing visibility on our websites.

Accordion example

The bootstrap collapse component creates accordions. Unlike the traditional accordion behavior, the bootstrap approach allows you to design a vertically stacked group of collapsible panels that can only be expanded one at a time. Let’s see an example of an accordion in use in a Frequently Asked Questions application:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>FAQ App</title>
  </head>
<body>
  <div class="accordion" id="accordionExample">
      <div class="accordion-item">
        <h2 class="accordion-header">
          <button
            class="accordion-button"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#collapseOne"
            aria-expanded="true"
            aria-controls="collapseOne"
          >
          	What is React?
          </button>
        </h2>
        <div
          id="collapseOne"
          class="accordion-collapse collapse show"
          data-bs-parent="#accordionExample"
        >
          <div class="accordion-body">
            React is a free and open-source front-end JavaScript library for building user interfaces based on components
          </div>
        </div>
      </div>
      <div class="accordion-item">
        <h2 class="accordion-header">
          <button
            class="accordion-button collapsed"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#collapseTwo"
            aria-expanded="false"
            aria-controls="collapseTwo"
          >
            What is React used for?
          </button>
        </h2>
        <div
          id="collapseTwo"
          class="accordion-collapse collapse"
          data-bs-parent="#accordionExample"
        >
          <div class="accordion-body">
           React can be used to build web, mobile, and desktop applications, making it a versatile framework for cross-platform development.
          </div>
        </div>
      </div>
      <div class="accordion-item">
        <h2 class="accordion-header">
          <button
            class="accordion-button collapsed"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#collapseThree"
            aria-expanded="false"
            aria-controls="collapseThree"
          >
            Is React a front-end or backend?
          </button>
        </h2>
        <div
          id="collapseThree"
          class="accordion-collapse collapse"
          data-bs-parent="#accordionExample"
        >
          <div class="accordion-body">
            React is a front-end JavaScript library.
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Since we’ll be using HTML, we can simply include the Bootstrap CDN in our HTML file. You can get the CDN from the Bootstrap website. See this example live here.

From the example above, the accordion utilizes the Bootstrap Collapse component to manage the collapsible behavior of the sections.

  • Accordion Structure: The HTML structure includes a container with the ID accordionExample, which will house the accordion.

  • Control Element’s HTML Element: The control element is the button inside the card header, responsible for triggering the collapse effect.

  • Collapse Element: Each collapsible element is represented by a card within the accordion.

  • Expanded False Aria Controls: The aria-expanded=”true” attribute on the button signifies that the collapsible element is initially expanded.

  • Collapsible Element: The collapsible element, identified by #collapseOne, #collapseTwo, and #collapseThree, contains the content that will be hidden or revealed.

  • Automatically Assign Control: The data-toggle=”collapse” and the elements data attributes automatically assign the button as the control for the collapsible element.

  • Hide Multiple Elements: The data-parent=”#accordionExample” attribute ensures that only one collapsible element can be expanded at a time, achieving the accordion behavior.

  • Control Element: The button serves as the control element, enabling users to toggle the visibility of the content within the associated collapsible element.

This accordion example shows how the Bootstrap Collapse component regulates content visibility within collapsible elements by smart use of data attributes and HTML structure, resulting in an engaging and user-friendly accordion layout.

Expand and Collapse Elements via Data Attributes

Expanding and collapsing components with data attributes in Bootstrap is a straightforward and declarative technique to control the appearance of an element on a webpage. You can effortlessly toggle the display of items by using certain data properties, eliminating the need for significant JavaScript code. Let’s look at how to accomplish this utilizing data attributes.

Basic example

We’ll start by looking at a basic example that uses a single data attribute. This attribute explicitly conveys a similar behavior to that of an accordion.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Single Data Attribute Example</title>
  </head>
<body>
  <div>
   <button type="button" class="btn btn-primary" data-toggle="collapse" data
	-target="#demo">Toggle Content
   </button>

   <div id="demo" class="collapse">
  Content to be collapsed or expanded.
  </div>
</div>
</body>
</html>
  • the example above uses the bootstrap collapse component through the data-toggle and data-target attributes.

  • The button, with the class btn btn-primary, acts as the control element for triggering the collapse effect. It contains the data-toggle=”collapse” and data-target=”#demo” attributes.

  • The single collapsible element tied to the button with the ID #demo is designated as the element to be collapsed, initially having the collapse class for hidden state.

A link with the href attribute can also be used to achieve the same result. For example:

  <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>

Before we proceed, I’d like to share a helpful resource that you might find beneficial. PureCode.ai is an AI-powered platform that’s built by developers for developers with over 10k AI-generated components that could improve your workflow when it comes to building applications. Make sure you check out PureCode.ai today!

Multiple targets

When working with the Bootstrap Collapse component, the ability to hide or reveal multiple elements simultaneously is a powerful feature that enhances the dynamics of web interfaces. This functionality is especially valuable when managing complex layouts or accordions where various sections need to be controlled collectively. Let’s delve into the concept of multiple targets.

  <div>
	<button type="button" class="btn btn-primary" data-toggle="collapse" data
	  -target=".multi-collapse">Toggle Content</button>

	<div id="target1" class="collapse multi-collapse">
  	  Content for target 1
	</div>
	<div id="target2" class="collapse multi-collapse">
  	  Content for target 2
	</div>
  </div>
  • The example uses the bootstrap Collapse component to enable the collapsing and expanding of multiple elements.

  • The button, with the class btn btn-primary, serves as the control element for triggering the collapse effect to enable the element’s collapse. It incorporates data-toggle=”collapse” and data-target=”.multi-collapse” attributes.

  • Multiple collapsible elements, identified by IDs (#target1 and #target2), share the same class. This grouping allows the button to toggle the visibility of both elements.

We can create more dynamic and user-friendly interfaces with the ability to switch multiple elements at the same time in Bootstrap Collapse. This feature aligns with Bootstrap’s simplicity while offering robust control over the visibility of content in different sections of a webpage. This is done by strategically utilizing data attributes and classes.

Expand and Collapse Elements via JavaScript

JavaScript dynamically toggles the collapse state without relying on data attributes. The JavaScript code directly interacts with the collapse state of the data target attribute. The script uses the classList property to add or remove the collapse class, mimicking the hide method. The JavaScript implementation allows us to customize the default collapse behavior based on specific requirements.

Let’s look at a basic implementation of a collapse element toggle with JavaScript.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>JavaScript Collapse Element</title>
  </head>
<body>
<button id="toggleButton" type="button" class="btn btn-primary">Toggle Content</button>

<div id="targetElement" class="collapse">
  Content to be collapsed or expanded.
</div>

<script>
  document.getElementById('toggleButton').addEventListener('click', function () {
    var target = document.getElementById('targetElement');
    if (target.classList.contains('collapse')) {
      target.classList.remove('collapse');
    } else {
      target.classList.add('collapse');
    }
  });
</script>
</body>
</html>
  • The button with the ID toggleButton serves as the control element to trigger the collapse effect.

  • The element with the ID targetElement is designated as the collapsible element, initially having the collapse class.

  • The JavaScript code enables manual control over the collapse function, offering flexibility and customization.

  • The JavaScript logic employs a conditional check to determine whether the target element currently has the collapse class. If it does, the class is removed, revealing the element. Conversely, if the class is not present, it is added, effectively hiding the target element.

Collapse Plugin

An advanced approach to expanding and collapsing elements involves harnessing the power of the bootstrap collapse plugin to automatically toggle a collapsible panel. The collapse JavaScript plugin streamlines the management of collapsible elements, offering us a more efficient and feature-rich solution.

A few classes are used by the collapse plugin to do the actual task of collapsing and expanding:

  • The .collapse hides content of the element to be collapsed.

  • The .collapse.show class shows the elements content

  • When the transition starts, the .collapsing class is added, and when it ends, it is removed. Its similar to what vanilla JavaScript does by removing and adding a classList.

We’ve seen the usage of the .collapse class in previous code samples.

To assign control of several collapsible elements automatically, simply add a data-target and data-toggle=”collapse” to the element. A CSS selector will need to be applied to the data-target attribute in order to apply the collapse. Since .collapse hides an element, make sure the collapsible element has the .collapse class added to it. If you want it to open by default, add the extra collapse.show class.

Below is an implementation of the plugin version using JavaScript.

<button id="toggleButton" type="button" class="btn btn-primary" data-toggle="collapse" data-target="#targetElement">Toggle Content</button>

<div id="targetElement" class="collapse">
  Content to be collapsed or expanded.
</div>

<script>
  document.getElementById('toggleButton').addEventListener('click', function () {
    $('#targetElement').collapse('toggle');
  });
</script>

For this example to work, you should have added bootstraps’ JavaScript CDN. Refer to the first example to see how to add it.

The button includes data-toggle=”collapse” and data-target=”#targetElement” attributes, specifying its role in toggling the collapse functionality and identifying the target element.

The JavaScript code uses jQuery (denoted by $) to interact with the bootstrap collapse JavaScript plugin.

The $(‘#targetElement’).collapse(‘toggle’) line instructs the plugin to toggle the collapse state of the element with the ID targetElement when the button is clicked.

There are some default methods that come with the plugin. Let’s look at them below.

// Toggle visibility of an element
$('#elementID').collapse('toggle');

// Show a collapsible element
$('#elementID').collapse('show');

// Hide a collapsible element
$('#elementID').collapse('hide');

// Destroy collapse functionality of an element
$('#elementID').collapse('dispose');

// Get collapse instance associated with an element
var collapseInstance = $('#elementID').data('bs.collapse');

TABLE HERE

Collapse indicators

Collapse indicators are illustrations or symbols that give users a visual clue as to whether collapsible panel or collapse element is expanded or collapsed. These indicators, when used in conjunction with Bootstrap and related frameworks, usually take the shape of arrows or icons that shift in orientation to indicate the collapsible element’s visibility state.

Bootstrap Collapse Indicators Example

<!-- collapsible element -->
<div class="container">
  <button class="btn btn-primary" data-toggle="collapse" data-target="#collapseExample">
    Toggle Content
  </button>

  <!-- Bootstrap's default collapse indicator (chevron icon) -->
  <span data-toggle="collapse" data-target="#collapseExample">
    <i class="fas fa-chevron-down"></i>
    <i class="fas fa-chevron-up"></i>
  </span>

<!-- element to be expanded -->
  <div class="collapse" id="collapseExample">
    Content to be toggled.
  </div>
</div>

The <i> elements with classes like fas fa-chevron-down and fas fa-chevron-up represent icons that change based on the collapse state of the collapse element.

Custom Collapse Indicator

 <!-- Custom collapse indicator are created using HTML entities (arrow) -->
  <span data-toggle="collapse" data-target="#customCollapse">
    <span class="arrow-down">▼</span>
    <span class="arrow-up" style="display: none;">▲</span>
  </span>

  <script>
//JavaScript is used to toggle the visibility of custom indicators based on the //collapse state
    $('#customCollapse').on('show.bs.collapse', function () {
      $('.arrow-down').hide();
      $('.arrow-up').show();
    });

    $('#customCollapse').on('hide.bs.collapse', function () {
      $('.arrow-up').hide();
      $('.arrow-down').show();
    });
  </script>
</div>

Wrap Up

To sum up, learning how to use the bootstrap collapse component offers up a world of possibilities for designing dynamic and intuitive user interfaces for websites. We have access to a variety of tools, such as data attributes for content toggling, JavaScript for enhanced control, and the collapse JavaScript plugin for streamlined functionality.
When implementing these strategies, take into account the particular requirements of your project and find the ideal harmony between usability, style, and usefulness. Have fun with coding!

Check out Purecode.ai‘s AI generated components today!

Favourite Jome

Favourite Jome