Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically toggle Bootstrap 5 collapse component

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?

like image 923
lonix Avatar asked May 19 '26 16:05

lonix


2 Answers

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();
like image 190
lonix Avatar answered May 21 '26 04:05

lonix


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 });

See https://github.com/twbs/bootstrap/blob/688bce4fa695cc360a0d084e34f029b0c192b223/js/src/collapse.js#L97-L99

    if (this._config.toggle) {
      this.toggle()
    }
like image 29
Ike Avatar answered May 21 '26 05:05

Ike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!