Collapse toggle lets you show or hide content smoothly on a webpage. It helps keep pages neat and easy to use.
Collapse toggle via JavaScript in Bootsrap
var myCollapse = new bootstrap.Collapse(element, options); // To toggle collapse via JavaScript: myCollapse.toggle();
element is the HTML element you want to collapse or expand.
options can include {toggle: true} to open immediately or false to stay closed.
var myCollapse = new bootstrap.Collapse(document.getElementById('myContent'));
myCollapse.toggle();var myCollapse = new bootstrap.Collapse(document.querySelector('.collapse'), {toggle: false}); // Starts collapsed, toggle later with myCollapse.toggle()
This example creates a button that toggles the visibility of some content below it. The content starts hidden. When you click the button, the content smoothly appears or disappears. The button text and aria-expanded attribute update for accessibility.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Bootstrap Collapse Toggle Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <main class="container py-4"> <h1>Collapse Toggle via JavaScript</h1> <button id="toggleBtn" class="btn btn-primary mb-3" aria-expanded="false" aria-controls="collapseExample"> Show Details </button> <div class="collapse" id="collapseExample"> <div class="card card-body"> This content is hidden or shown when you click the button above. </div> </div> </main> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> const collapseElement = document.getElementById('collapseExample'); const toggleBtn = document.getElementById('toggleBtn'); const bsCollapse = new bootstrap.Collapse(collapseElement, { toggle: false }); toggleBtn.addEventListener('click', () => { bsCollapse.toggle(); const expanded = toggleBtn.getAttribute('aria-expanded') === 'true'; toggleBtn.setAttribute('aria-expanded', String(!expanded)); toggleBtn.textContent = expanded ? 'Show Details' : 'Hide Details'; }); </script> </body> </html>
Always include aria-expanded and aria-controls on toggle buttons for accessibility.
Use Bootstrap's bundled JavaScript file to get all features without extra setup.
Start with {toggle: false} if you want the content hidden initially.
Use new bootstrap.Collapse(element) to control collapse with JavaScript.
Call toggle() to show or hide content smoothly.
Update button text and aria attributes for a better user experience.
Practice
toggle() method do when used with new bootstrap.Collapse(element) in Bootstrap?Solution
Step 1: Understand the collapse object
Thenew bootstrap.Collapse(element)creates a controller for the collapsible content.Step 2: Role of
Thetoggle()methodtoggle()method switches the content between visible and hidden states smoothly.Final Answer:
It shows the hidden content if collapsed, or hides it if shown. -> Option BQuick Check:
toggle() switches collapse state [OK]
- Thinking toggle disables collapse
- Confusing toggle with page reload
- Assuming toggle changes styles only
myCollapse in JavaScript?Solution
Step 1: Identify the element reference
The Bootstrap Collapse constructor requires a DOM element, not a selector string.Step 2: Correct syntax for element selection
Usingdocument.getElementById('myCollapse')returns the element to pass to the constructor.Final Answer:
const collapse = new bootstrap.Collapse(document.getElementById('myCollapse')); -> Option CQuick Check:
Pass DOM element, not selector string [OK]
- Passing selector string instead of element
- Omitting 'new' keyword
- Using undefined Collapse without bootstrap prefix
const collapse = new bootstrap.Collapse(document.getElementById('content'), { toggle: false });
document.getElementById('toggleBtn').addEventListener('click', () => {
collapse.toggle();
});The content is initially hidden.
Solution
Step 1: Understand initial state and options
The content starts hidden andtoggle: falsemeans it won't auto-toggle on creation.Step 2: Effect of calling
Callingtoggle()on clicktoggle()manually switches the state, so hidden content becomes visible.Final Answer:
The content will become visible. -> Option AQuick Check:
Manual toggle() shows hidden content [OK]
- Thinking toggle:false disables toggle() method
- Assuming content stays hidden without auto toggle
- Confusing toggle() with remove()
const collapse = new bootstrap.Collapse('content');
document.getElementById('btn').addEventListener('click', () => {
collapse.toggle();
});Solution
Step 1: Check constructor argument
The constructor expects a DOM element, but 'content' is a string selector, which is incorrect.Step 2: Correct way to pass element
Usedocument.getElementById('content')to get the element before passing it.Final Answer:
The selector 'content' should be a DOM element, not a string. -> Option AQuick Check:
Pass DOM element, not string selector [OK]
- Passing string selector instead of element
- Assuming toggle() is unavailable
- Incorrect event listener target
const collapse = new bootstrap.Collapse(document.getElementById('panel'), { toggle: false });
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', () => {
collapse.toggle();
if (btn.textContent === 'Show') {
btn.textContent = 'Hide';
} else {
btn.textContent = 'Show';
}
});Solution
Step 1: Check toggle and button text update order
The code callscollapse.toggle()then updates the button text based on current text, which is logical.Step 2: Validate textContent usage and event setup
UsingtextContentis correct for plain text updates, and the collapse instance is created once outside the event.Final Answer:
This code works correctly to toggle and update button text. -> Option DQuick Check:
Toggle then update textContent works [OK]
- Updating text before toggle causing mismatch
- Using innerHTML unnecessarily
- Recreating collapse instance on every click
Ready to prove it?
Pass the test and this pattern moves unknown
