I've not had to work with the Collapse feature in Bootstrap 5 until today and I strongly dislike it!
If I have a simple setup with a collapsible element - hidden initially - and a button to toggle its visibility, like this:
<button class="btn btn-primary" id="toggleDetails">Show Details</button>
<div class="collapse border mt-2 p-2" id="details">
Here is some information.
</div>
and some Javascript like this:
const details = document.getElementById("details");
const detailsCollapse = bootstrap.Collapse.getOrCreateInstance(details);
const btn = document.getElementById("toggleDetails");
btn.addEventListener("click", (e) => {
detailsCollapse.toggle();
});
why does the getOrCreateInstance toggle the collapsible element's visibility? Surely its only job is to get the collapse instance. It's absolutely infuriating. Am I doing something wrong? If not, how can I get the collapse instance without toggling it? Obviously in my actual code the setup is more complex than this but this issue is currently holding me up.
There's a fiddle showing the problem here.
Add toggle: false option
The default behavior is
Toggles the collapsible element on invocation.
const details = document.getElementById("details");
const detailsCollapse = bootstrap.Collapse.getOrCreateInstance(details, {
toggle: false
})
const btn = document.getElementById("toggleDetails");
btn.addEventListener("click", (e) => {
detailsCollapse.toggle();
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<button class="btn btn-primary" id="toggleDetails">Show Details</button>
<div class="collapse border mt-2 p-2" id="details">
Here is some information.
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With