Today was my first encounter with the Collapse feature in Bootstrap 5, and I have to admit, I am not a fan!
Imagine a scenario where I have a collapsible element that is initially hidden, and a button to toggle its visibility, like so:
<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>
Accompanied by some Javascript code:
const details = document.getElementById("details");
const detailsCollapse = bootstrap.Collapse.getOrCreateInstance(details);
const btn = document.getElementById("toggleDetails");
btn.addEventListener("click", (e) => {
detailsCollapse.toggle();
});
My frustration stems from the fact that the getOrCreateInstance
function not only retrieves the collapse instance but also toggles its visibility. This seems counterintuitive to me. Is there a way to obtain the collapse instance without toggling it? I have a more complex setup in my actual code, and this issue is currently causing a delay in my project.
You can view the problem in this fiddle.