Bootstrap - Collapse

-

What is Bootstrap Collapse?

Bootstrap Collapse is a feature that lets you create collapsible content sections on your web pages. It provides a way to hide and show content by toggling the visibility of elements. With Bootstrap Collapse, you can create accordion-like structures, show/hide additional information, or create interactive elements that expand and collapse when clicked.

Why use Bootstrap Collapse? Here are several reasons why you might want to use this feature in your web projects:

Reason Description
Space-saving Collapse lets you hide content that is not immediately necessary, saving space on your web page. Users can then choose to expand the content they are interested in, keeping the page clean and organized.
User interaction By using Collapse, you encourage user interaction with your website. Users can click on elements to reveal more information, making the experience more engaging and interactive.
Progressive disclosure Collapse helps in presenting information progressively. You can initially show a summary or a small portion of content, and then allow users to expand it to view more details. This approach is useful when dealing with lengthy content or complex information.
Flexibility Bootstrap Collapse is flexible and can be used in various scenarios. You can create single collapsible elements, accordion-like structures where only one item is expanded at a time, or even nested collapsible elements.
Easy implementation Bootstrap provides a simple way to implement Collapse functionality. With just a few HTML attributes and minimal JavaScript, you can quickly add collapsible elements to your web pages.

By using Bootstrap Collapse, you can improve the user experience, make your web pages more interactive, and present content in a more organized and space-efficient way.

Creating a Collapse Element

To create a Collapse element in Bootstrap, you need to use the data-bs-toggle attribute on a button or link element. This attribute tells Bootstrap that the element is responsible for toggling the visibility of a Collapse element.

Example: Button that toggles a Collapse element

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Toggle Collapse
</button>

The data-bs-toggle="collapse" attribute specifies that the button should toggle a Collapse element.

Next, you need to specify the target element that should be collapsed or expanded. You do this using the data-bs-target attribute on the button or link element. The value of data-bs-target should be a CSS selector that points to the element you want to collapse or expand.

Button that targets an element with the ID collapseExample

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Toggle Collapse
</button>

The data-bs-target="#collapseExample" attribute tells Bootstrap to toggle the visibility of the element with the ID collapseExample.

Let's put it all together and create a basic Collapse element:

Example: Basic Collapse element

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Toggle Collapse
</button>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    This is the collapsible content. It is hidden by default and will be shown when the button is clicked.
  </div>
</div>
  • The button has the data-bs-toggle="collapse" attribute to specify that it controls a Collapse element.
  • The button's data-bs-target="#collapseExample" attribute targets the element with the ID collapseExample.
  • The <div> element with the class collapse and the ID collapseExample is the collapsible content. It is initially hidden.
  • The content inside the <div> is placed within a <div> with the classes card and card-body to give it a card-like appearance.

When the button is clicked, Bootstrap will toggle the visibility of the <div> with the ID collapseExample, showing or hiding the content inside it.

You can put any content you want inside the collapsible <div>, such as text, images, or other HTML elements. Bootstrap will handle the toggling of the visibility based on the button's state.

That's how you create a basic Collapse element in Bootstrap. With this structure in place, you can easily add collapsible content to your web pages and provide a way for users to show or hide it as needed.

Controlling Collapse Behavior

Bootstrap Collapse offers several ways to control the behavior of collapsible elements. You can create accordion-like structures, set the initial state of a Collapse element, and trigger the Collapse with JavaScript.

To create an accordion-like behavior, where only one Collapse element is expanded at a time, you can use the data-bs-parent attribute. When you add data-bs-parent to a Collapse element and specify a parent container, Bootstrap will make sure that only one Collapse element within that container is expanded at a time.

Example: Accordion-like behavior

<div id="accordion">
  <div class="card">
    <div class="card-header">
      <button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" data-bs-parent="#accordion">
        Item #1
      </button>
    </div>
    <div id="collapseOne" class="collapse show">
      <div class="card-body">
        Content for item #1
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header">
      <button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" data-bs-parent="#accordion">
        Item #2
      </button>
    </div>
    <div id="collapseTwo" class="collapse">
      <div class="card-body">
        Content for item #2
      </div>
    </div>
  </div>
</div>

To set the initial state of a Collapse element, add the class="collapse" to the element. By default, the Collapse element will be hidden. To show the Collapse element initially, you can add the show class along with the collapse class.

Example: Setting initial state

<div id="collapseExample" class="collapse show">
  <!-- Content goes here -->
</div>

To trigger the Collapse element with JavaScript, Bootstrap provides JavaScript methods to show, hide, or toggle a Collapse element.

Example: Triggering Collapse with JavaScript

var collapseElement = document.getElementById('collapseExample');
var collapse = new bootstrap.Collapse(collapseElement);

// Show the Collapse element
collapse.show();

// Hide the Collapse element
collapse.hide();

// Toggle the Collapse element
collapse.toggle();

In this code, we get a reference to the Collapse element using document.getElementById(). Then, we create a new bootstrap.Collapse instance by passing the element to the Collapse constructor. We can call the show(), hide(), or toggle() methods on the Collapse instance to control the visibility of the Collapse element.

Collapse Options

Bootstrap Collapse provides more options and features to improve the functionality and accessibility of collapsible elements. Let's look at some of these options.

Horizontal Collapse

By default, Bootstrap Collapse works vertically, meaning the content expands and collapses vertically. However, you can also create a horizontal Collapse by adding the collapse-horizontal class to the Collapse element.

Horizontal Collapse Example

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Toggle Collapse
</button>

<div class="collapse collapse-horizontal" id="collapseExample">
  <div class="card card-body" style="width: 300px;">
    This is a horizontal Collapse element. The content expands and collapses horizontally.
  </div>
</div>

The collapse-horizontal class is added to the <div> element with the ID collapseExample. This tells Bootstrap to apply horizontal Collapse behavior to the element. The content inside the <div> will expand and collapse horizontally when the button is clicked.

Multiple Targets

Bootstrap Collapse also allows you to target multiple elements with a single trigger. You can specify multiple target elements by using a comma-separated list of selectors in the data-bs-target attribute.

Multiple Targets Example

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne, #collapseTwo">
  Toggle Multiple Collapses
</button>

<div class="collapse" id="collapseOne">
  <div class="card card-body">
    Content for Collapse One
  </div>
</div>

<div class="collapse" id="collapseTwo">
  <div class="card card-body">
    Content for Collapse Two
  </div>
</div>

The button's data-bs-target attribute targets both #collapseOne and #collapseTwo. When the button is clicked, both Collapse elements will be toggled at the same time.

Accessibility Considerations

When using Bootstrap Collapse, it's important to consider accessibility to provide a user-friendly experience for all users, including those using assistive technologies. Here are a few accessibility considerations:

Consideration Description
Meaningful text Use clear and descriptive text for the trigger element (button or link) to make it clear what action will be performed when clicked.
aria-controls Associate the trigger element with the collapsible content using the aria-controls attribute. This attribute should reference the ID of the collapsible content.
aria-expanded Use the aria-expanded attribute on the trigger element to show the current state of the Collapse element. Set it to true when the content is expanded and false when it is collapsed.

Accessibility Considerations Example

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
  Toggle Collapse
</button>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Collapsible content goes here...
  </div>
</div>
  • The button text clearly indicates the action of toggling the Collapse element.
  • The aria-controls attribute on the button references the ID of the collapsible content collapseExample.
  • The aria-expanded attribute on the button is initially set to false to show that the content is collapsed by default.

By following these accessibility considerations, you can create collapsible elements that are more inclusive and user-friendly for all users.

Styling Collapse Elements

When using Bootstrap Collapse, you can change the look of the Collapse button and the collapsed content to match your website's design. Bootstrap provides classes and styles that you can use to change the look and feel of the Collapse elements.

Changing Collapse Button Look

The Collapse button is usually a <button> or <a> element that triggers the Collapse functionality. Bootstrap provides classes that you can apply to the button to change its look.

Collapse Button Example

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Primary Button
</button>

<button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Secondary Button
</button>

<a class="btn btn-info" data-bs-toggle="collapse" href="#collapseExample" role="button">
  Info Link
</a>

In the example above, the btn class is used to style the buttons as Bootstrap buttons, and the btn-primary, btn-secondary, and btn-info classes are used to apply different color schemes. You can choose from button styles provided by Bootstrap or create your own styles.

Styling the Collapsed Content

The collapsed content is usually wrapped inside a <div> element with the collapse class. You can apply classes or custom styles to the collapsed content to control its look.

Collapsed Content Example

<div class="collapse" id="collapseExample">
  <div class="card">
    <div class="card-body">
      <h5 class="card-title">Card Title</h5>
      <p class="card-text">Some content inside the collapsed card.</p>
      <a href="#" class="btn btn-primary">Go somewhere</a>
    </div>
  </div>
</div>

In this example, the collapsed content is wrapped inside a <div> with the card class, which gives it a card-like look. The card-body class is used to add padding to the card's content, and classes like card-title and card-text are used to style the text inside the card.

You can further change the look of the collapsed content by applying your own CSS styles or using Bootstrap's utility classes.

Transitions and Animations

Bootstrap Collapse comes with built-in transitions and animations that make the expanding and collapsing of content smooth and visually appealing. By default, the Collapse elements have a sliding animation when they are shown or hidden.

If you want to change the transition duration or disable the animations, you can override the default styles using CSS.

Transitions and Animations Example

.collapse {
  transition: height 0.5s ease;
}

.collapsing {
  transition: height 0.5s ease;
}

In this CSS code, the transition property is used to set the transition duration and easing function for the collapse and collapsing classes. The height property is used to animate the height of the Collapse element.

You can experiment with different transition properties and values to get the desired animation effect.

By changing the look of the Collapse button, styling the collapsed content, and modifying the transitions and animations, you can create visually appealing Collapse elements that align with your website's design.

Collapse Events

Bootstrap Collapse has events that you can use to find and respond to the states of a Collapse element. These events are triggered when a Collapse element is shown or hidden, letting you do actions or run custom code.

The show.bs.collapse event is fired when the show instance method is called. It happens before the Collapse element starts to expand. You can use this event to do any setup tasks before the Collapse element is visible.

Example: show.bs.collapse

var collapseElement = document.getElementById('collapseExample');
collapseElement.addEventListener('show.bs.collapse', function () {
  console.log('Collapse is about to be shown');
  // You can do any setup tasks here
});

The shown.bs.collapse event is fired when a Collapse element has finished expanding and is fully visible. This event is triggered after the Collapse element has completed its transition.

Example: shown.bs.collapse

var collapseElement = document.getElementById('collapseExample');
collapseElement.addEventListener('shown.bs.collapse', function () {
  console.log('Collapse is fully shown');
  // You can do any actions or update the UI here
});

Bootstrap Collapse also has events for the hiding process. The hide.bs.collapse event is fired when the hide instance method is called. It happens before the Collapse element starts to collapse.

Example: hide.bs.collapse

var collapseElement = document.getElementById('collapseExample');
collapseElement.addEventListener('hide.bs.collapse', function () {
  console.log('Collapse is about to be hidden');
  // You can do any cleanup or setup tasks here
});

The hidden.bs.collapse event is fired when a Collapse element has finished collapsing and is fully hidden. This event is triggered after the Collapse element has completed its transition.

Example: hidden.bs.collapse

var collapseElement = document.getElementById('collapseExample');
collapseElement.addEventListener('hidden.bs.collapse', function () {
  console.log('Collapse is fully hidden');
  // You can do any actions or update the UI here
});

Example of listening to Collapse events

<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
  Toggle Collapse
</button>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Collapsed content goes here...
  </div>
</div>

<script>
  var collapseElement = document.getElementById('collapseExample');

  collapseElement.addEventListener('show.bs.collapse', function () {
    console.log('Collapse is about to be shown');
    // Do any setup tasks
  });

  collapseElement.addEventListener('shown.bs.collapse', function () {
    console.log('Collapse is fully shown');
    // Do any actions or update the UI
  });

  collapseElement.addEventListener('hide.bs.collapse', function () {
    console.log('Collapse is about to be hidden');
    // Do any cleanup or setup tasks
  });

  collapseElement.addEventListener('hidden.bs.collapse', function () {
    console.log('Collapse is fully hidden');
    // Do any actions or update the UI
  });
</script>

By using Collapse events, you can create interactive experiences with Bootstrap Collapse. You can update the UI, start animations, load data, or do any other custom actions in response to the state changes of a Collapse element.

Collapse Methods

Bootstrap Collapse has JavaScript methods that let you control the state of Collapse elements. These methods let you show, hide, or toggle a Collapse element programmatically, and also let you check the current state of a Collapse element.

One of the most common methods is the collapseInstance.toggle() method. This method toggles the visibility of a Collapse element. If the Collapse element is currently hidden, calling collapseInstance.toggle() will show it. If the Collapse element is currently visible, calling collapseInstance.toggle() will hide it.

Example: Toggling a Collapse Element

var collapseElement = document.getElementById('collapseExample');
var collapseInstance = new bootstrap.Collapse(collapseElement);

// Toggle the Collapse element
collapseInstance.toggle();

In this code, we get a reference to the Collapse element using document.getElementById(). Then, we create a new bootstrap.Collapse instance by passing the element to the Collapse constructor. We assign the instance to the variable collapseInstance.

To toggle the visibility of the Collapse element, we call the toggle() method on the collapseInstance. This will show the Collapse element if it's currently hidden, or hide it if it's currently visible.

You can also show or hide a Collapse element programmatically using the collapseInstance.show() and collapseInstance.hide() methods.

Example: Showing and Hiding a Collapse Element

var collapseElement = document.getElementById('collapseExample');
var collapseInstance = new bootstrap.Collapse(collapseElement);

// Show the Collapse element
collapseInstance.show();

// Hide the Collapse element
collapseInstance.hide();

The show() method expands the Collapse element, making it visible, while the hide() method collapses the Collapse element, hiding it from view.

Another useful method is collapseInstance.dispose(). This method destroys the Collapse instance, removing any event listeners and data associated with it. You can use this method when you no longer need the Collapse functionality for a particular element.

Example: Disposing a Collapse Instance

var collapseElement = document.getElementById('collapseExample');
var collapseInstance = new bootstrap.Collapse(collapseElement);

// Check if the Collapse element is currently shown
if (collapseElement.classList.contains('show')) {
  console.log('Collapse element is currently shown');
} else {
  console.log('Collapse element is currently hidden');
}

// Dispose the Collapse instance when no longer needed
collapseInstance.dispose();

In this code, we check the current state of the Collapse element by using the classList.contains() method to see if the Collapse element has the show class. If it does, it means the Collapse element is currently shown. If it doesn't, it means the Collapse element is currently hidden.

After checking the state, we call the dispose() method on the collapseInstance to destroy the Collapse instance when it's no longer needed. This is a good practice to free up resources and avoid memory leaks.

By using the Collapse methods provided by Bootstrap, you can programmatically control the behavior of Collapse elements and create dynamic and interactive user experiences.

Integrating Collapse with Other Components

Bootstrap Collapse can be used with other Bootstrap components to create dynamic and interactive user interfaces. Here's how you can integrate Collapse with Navbars, Cards, Modals, and Popovers.

Using Collapse with Navbars

You can use Collapse to create a collapsible navigation menu within a Navbar. This is useful when you have many navigation items and want to hide them on small screens.

Example: Collapsible Navigation Menu within a Navbar

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">My Website</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Services</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Contact</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

Creating Accordion-like Structures with Cards

Bootstrap Collapse can be used with the Card component to create accordion-like structures. Accordions allow users to expand and collapse sections of content by clicking on a header.

Example: Accordion-like Structure with Card Component

<div class="accordion" id="myAccordion">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne">
          Section 1
        </button>
      </h2>
    </div>
    <div id="collapseOne" class="collapse show" data-bs-parent="#myAccordion">
      <div class="card-body">
        Content for Section 1
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo">
          Section 2
        </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" data-bs-parent="#myAccordion">
      <div class="card-body">
        Content for Section 2
      </div>
    </div>
  </div>
</div>

Collapse in Modals and Popovers

Collapse can also be used within Modals and Popovers to show and hide content. This can be useful when you want to provide more information or options without cluttering the interface.

Example: Collapse within Modal Body

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
  Open Modal
</button>

<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal Title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Some content in the modal body.</p>
        <button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">
          Show More
        </button>
        <div class="collapse" id="collapseExample">
          <div class="mt-3">
            Additional content that can be collapsed.
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

By integrating Collapse with other Bootstrap components like Navbars, Cards, Modals, and Popovers, you can create dynamic user interfaces. Collapse lets you show and hide content on demand, allowing users to access information or options when needed while keeping the interface clean.