bootstrap_ref_js_collapse
Bootstrap 5 JS Collapse
Section titled “Bootstrap 5 JS Collapse”JS Collapse (collapse.js)
Section titled “JS Collapse (collapse.js)”The Collapse JavaScript plugin allows you to toggle the visibility of content. It’s perfect for creating accordions and expandable navigation menus.
Bootstrap’s JavaScript components, including Collapse, are typically included in bootstrap.bundle.min.js, which also bundles Popper.js (a dependency for tooltips and popovers, but not directly for collapse). The transition effects are part of Bootstrap’s core CSS/JS.
The Collapse Plugin Classes
Section titled “The Collapse Plugin Classes”ClassDescriptionExample
`.collapse`Hides the content by default.`Try it: Add to a <div> to make it collapsible.`
`.collapse.show`Shows the content by default. (Replaces the older `.collapse.in`)`Try it: Add to a collapsible <div> to make it visible initially.`
`.collapsing`Applied automatically by Bootstrap during the transition (when opening or closing).`This class is managed by the plugin.`Via data-bs-* Attributes
Section titled “Via data-bs-* Attributes”You can easily control collapsible elements using data-bs-* attributes without writing any JavaScript. Add data-bs-toggle="collapse" to a button or link, and data-bs-target="#selector" to point to the collapsible element’s ID. The collapsible element itself must have the .collapse class. To make it open by default, add the .show class as well.
For accordion-like group management (where opening one item closes others in the same group), add the data-bs-parent="#selector" attribute to each collapsible item’s trigger, pointing to a common parent element.
Practical Application: Ideal for FAQ sections, where clicking a question reveals the answer.
Via JavaScript
Section titled “Via JavaScript”Enable collapse functionality manually with JavaScript:
// Initialize a collapse elementconst myCollapseElement = document.getElementById('myCollapsibleElement');const bsCollapse = new bootstrap.Collapse(myCollapseElement, { toggle: false // Set to false to prevent toggling on initialization});
// To toggle it later:bsCollapse.toggle();
// To show it:bsCollapse.show();
// To hide it:bsCollapse.hide();
// To dispose of the collapse instance:bsCollapse.dispose();
// For all collapse triggers:const collapseTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="collapse"]'));const collapseList = collapseTriggerList.map(function (collapseTriggerEl) { // You might want to get the target from data-bs-target and initialize that element // This example just shows initialization from a trigger, which might not be what you want for direct manipulation. // Better to initialize the collapsible element directly. return new bootstrap.Collapse(collapseTriggerEl); // Or better: new bootstrap.Collapse(document.querySelector(collapseTriggerEl.getAttribute('data-bs-target')))});
// Common Obstacle: Ensuring the correct element is targeted for initialization. Always initialize the collapsible content element, not just the trigger.Collapse Options
Section titled “Collapse Options”Options can be passed via data-bs-* attributes or JavaScript. For data attributes, append the option name to data-bs-, as in data-bs-parent="".
NameTypeDefaultDescription (Bootstrap 5)
`parent`selector | DOM element | jQuery object`null`If a selector or DOM node is provided, all collapsible elements under the specified parent will be closed when this collapsible item is shown. (This is the core of accordion behavior). Use `data-bs-parent` attribute.
`toggle`boolean`true`Toggles the collapsible element on invocation (i.e., when initialized via JavaScript and this is true, it will toggle state).Collapse Methods
Section titled “Collapse Methods”The following table lists available collapse methods. These are called on the Collapse instance (e.g., bsCollapse.toggle()).
MethodDescription
`toggle()`Toggles a collapsible element to shown or hidden.
`show()`Shows a collapsible element.
`hide()`Hides a collapsible element.
`dispose()`Destroys an element’s collapse. (Removes stored data on the DOM element)
`getInstance(element)`Static method which allows you to get the collapse instance associated with a DOM element.
`getOrCreateInstance(element, [config])`Static method which allows you to get the collapse instance associated with a DOM element, or create a new one in case it wasn’t initialized.Collapse Events
Section titled “Collapse Events”Bootstrap’s collapse plugin fires a few events for hooking into collapse functionality. All events are fired at the collapsible element itself (e.g., the <div class="collapse">).
EventDescriptionExample (Vanilla JS)
`show.bs.collapse`This event fires immediately when the `show` instance method is called.`myCollapsibleElement.addEventListener('show.bs.collapse', function () { /* action */ })`
`shown.bs.collapse`This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).`myCollapsibleElement.addEventListener('shown.bs.collapse', function () { /* action */ })`
`hide.bs.collapse`This event is fired immediately when the `hide` method has been called.`myCollapsibleElement.addEventListener('hide.bs.collapse', function () { /* action */ })`
`hidden.bs.collapse`This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).`myCollapsibleElement.addEventListener('hidden.bs.collapse', function () { /* action */ })`
Learning Tip: Use these events to trigger other actions, like loading content dynamically when a section is shown, or changing icons on the trigger button.Simple Collapsible Example
Section titled “Simple Collapsible Example”The following example makes a button toggle the expanding and collapsing content of another element:
<button class="btn btn-info" type="button" data-bs-toggle="collapse" data-bs-target="#demoContent" aria-expanded="false" aria-controls="demoContent"> Simple collapsible</button>
<div class="collapse" id="demoContent"> <div class="card card-body mt-2"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div></div>
<!-- To make it open by default, change class="collapse" to class="collapse show" on the #demoContent div -->Accordion (using Bootstrap 5 Card and Accordion components)
Section titled “Accordion (using Bootstrap 5 Card and Accordion components)”The following example shows a simple accordion. Bootstrap 5 has dedicated accordion classes that build upon the collapse plugin and card components.
<div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </button> </h2> <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> **This is the first item's accordion body.** It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header" id="headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Collapsible Group Item #2 </button> </h2> <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample"> <div class="accordion-body"> **This is the second item's accordion body.** It is hidden by default. The `.accordion-button` gets an arrow icon automatically via CSS, which rotates when collapsed/expanded. </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header" id="headingThree"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Collapsible Group Item #3 </button> </h2> <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample"> <div class="accordion-body"> **This is the third item's accordion body.** This item is also hidden by default. </div> </div> </div></div>
<!-- Resource: For more on accordions, visit https://getbootstrap.com/docs/5.3/components/accordion/ -->Expand and Collapse Toggle Icon & Text (Modern Approach)
Section titled “Expand and Collapse Toggle Icon & Text (Modern Approach)”Bootstrap 5’s .accordion-button automatically handles a default chevron icon. If you need custom icons or text changes for a non-accordion collapse, you can use JavaScript event listeners. Glyphicons are no longer part of Bootstrap; consider using Bootstrap Icons (SVGs) or another icon library.
<!-- HTML for a custom toggle button and content --><button id="customToggleButton" class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#customCollapseContent" aria-expanded="false" aria-controls="customCollapseContent"> <!-- Bootstrap Icon (example, ensure you've included Bootstrap Icons CSS/SVG sprite) --> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down me-2" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/></svg> <span>Open</span></button><div class="collapse" id="customCollapseContent"> <div class="card card-body mt-2"> Content here. </div></div>
<script>document.addEventListener('DOMContentLoaded', function () { const collapseElement = document.getElementById('customCollapseContent'); const buttonElement = document.getElementById('customToggleButton'); const buttonIcon = buttonElement.querySelector('svg'); // Or your icon element const buttonTextSpan = buttonElement.querySelector('span');
collapseElement.addEventListener('show.bs.collapse', function () { buttonTextSpan.textContent = 'Close'; if (buttonIcon) { // Example: Rotate icon or change to a different icon buttonIcon.style.transform = 'rotate(180deg)'; // For Bootstrap Icons, you might swap classes for a different icon: // buttonIcon.classList.remove('bi-chevron-down'); // buttonIcon.classList.add('bi-chevron-up'); } });
collapseElement.addEventListener('hide.bs.collapse', function () { buttonTextSpan.textContent = 'Open'; if (buttonIcon) { buttonIcon.style.transform = 'rotate(0deg)'; // buttonIcon.classList.remove('bi-chevron-up'); // buttonIcon.classList.add('bi-chevron-down'); } });});</script>
<!-- Note: The icon SVG is an example. For cleaner icon management, consider Bootstrap Icons: https://icons.getbootstrap.com/ -->