Building Expandable Sections with Bootstrap JS Collapse
Need to show or hide sections of content with a smooth animation — like FAQs, dropdowns, or menus? Bootstrap’s Collapse component gives you everything you need using just HTML and a touch of JavaScript.
In this post, we’ll walk through how to use the Bootstrap Collapse component and how to control it with both data attributes and JavaScript methods.
Step 1: Include Bootstrap
Use the official Bootstrap CDN or your own build — just make sure JavaScript is included.
Basic Collapse Example (With data-bs-toggle)
✅ This works without writing any JavaScript. Bootstrap automatically handles the collapsing behavior.
How It Works
-
data-bs-toggle="collapse"turns a button or link into a trigger. -
data-bs-target="#id"connects the trigger to the collapsible content. -
The collapsible content must have the
collapseclass.
Collapse Inside an Accordion
Use this pattern to create multiple collapsible panels — but only one stays open at a time.
data-bs-parent makes it behave like a traditional accordion: only one section is open at a time.
JavaScript API: Programmatic Control
You can also control collapse behavior using Bootstrap’s JS API.
HTML:
JavaScript:
⚙️ Collapse Options & Events
| Option | Description |
|---|---|
show() |
Expands the element |
hide() |
Collapses the element |
toggle() |
Toggles the visibility |
Bootstrap also provides events like:
✅ Use Cases
-
FAQs (accordion style)
-
Mobile menus
-
Read-more sections
-
Filters/sidebars in eCommerce UIs
Final Thoughts
Bootstrap’s Collapse component gives you flexible content toggling with smooth animations, zero dependencies, and clean markup. Whether you’re building a sidebar, FAQ, or dynamic content section, the Collapse utility lets you manage visibility with ease.
