Reputation: 21081
I'm using a boostrap 5 "collapse", using the data attributes approach. It works as expected. I can click the button to collapse/expand the collapsible items.
The docs state I can toggle the state manually, like so:
let element = document.querySelector('#my-collapse');
bootstrap.Collapse.getInstance(element).toggle();
However that fails, as getInstance
returns null
.
Strangely, if I click the collapse button, then use that code, it works.
How do I ensure the code works without first "priming" the collapse component?
Upvotes: 8
Views: 4401
Reputation: 21
Bootstrap Collapse by default runs some 'auto-toggle' in constructor.
Add some config that turns this first toggling of solves the issue:
let element = document.querySelector('#my-collapse');
bootstrap.Collapse.getOrCreateInstance(element, { toggle: false });
if (this._config.toggle) {
this.toggle()
}
Upvotes: 2
Reputation: 2141
The code below insures that collapse instance is not null:
let element = document.querySelector('#my-collapse');
// try to get collapse instance
let bsCollapse = bootstrap.Collapse.getInstance(element);
// if the instance is not yet initialized then create new collapse
if (bsCollapse === null) {
bsCollapse = new bootstrap.Collapse(element, {
toggle: false // this parameter is important!
})
}
bsCollapse.show();
Upvotes: 2
Reputation: 21081
I think when using data attributes, the bootstrap component is only created on demand - i.e. when the collapse button is clicked for the first time. That would explain the behaviour I've noted above.
So the solution is to use getOrCreateInstance
instead:
let element = document.querySelector('#my-collapse');
bootstrap.Collapse.getOrCreateInstance(element).toggle();
Upvotes: 5