Skip to content

Commit c033fd4

Browse files
docs: clarify carousel getInstance timing and pause in events
Add two warning callouts to the carousel documentation: - In "Via JavaScript": document that `Carousel.getInstance` returns `null` for uninitialized carousels and recommend `getOrCreateInstance` or the `window` `load` event as alternatives. - In "Events": clarify that calling `pause` inside a `slide.bs.carousel` handler has no effect and recommend using `slid.bs.carousel` instead. Fixes #35722 Signed-off-by: Pierluigi Lenoci <pierluigilenoci@gmail.com>
1 parent a583d9a commit c033fd4

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

site/src/content/docs/components/carousel.mdx

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,21 @@ Call carousel manually with:
349349
const carousel = new bootstrap.Carousel('#myCarousel')
350350
```
351351

352+
<Callout type="warning">
353+
`Carousel.getInstance` will return `null` unless the carousel has already been initialized (either explicitly via the constructor, or automatically via `data-bs-ride`). If your carousel contains images or other asynchronous content, auto-initialization may not have completed by the time your script runs. To avoid a `null` reference, either initialize the carousel explicitly with the constructor, use `getOrCreateInstance`, or defer your code until the `window` `load` event:
354+
355+
```js
356+
// Option 1 – use getOrCreateInstance (recommended)
357+
const carousel = bootstrap.Carousel.getOrCreateInstance('#myCarousel')
358+
359+
// Option 2 – wait for the window load event
360+
window.addEventListener('load', () => {
361+
const carousel = bootstrap.Carousel.getInstance('#myCarousel')
362+
// carousel is now guaranteed to be initialized
363+
})
364+
```
365+
</Callout>
366+
352367
### Options
353368

354369
<JsDataAttributes />
@@ -411,6 +426,19 @@ All carousel events are fired at the carousel itself (i.e. at the `<div class="c
411426
| `slide.bs.carousel` | Fires immediately when the `slide` instance method is invoked. |
412427
</BsTable>
413428

429+
<Callout type="warning">
430+
Calling `pause` inside a `slide.bs.carousel` handler has no effect because the slide transition is already in progress. To programmatically pause the carousel after a slide change, use the `slid.bs.carousel` event instead:
431+
432+
```js
433+
const myCarousel = document.getElementById('myCarousel')
434+
435+
myCarousel.addEventListener('slid.bs.carousel', event => {
436+
const carousel = bootstrap.Carousel.getInstance(myCarousel)
437+
carousel.pause()
438+
})
439+
```
440+
</Callout>
441+
414442
```js
415443
const myCarousel = document.getElementById('myCarousel')
416444

0 commit comments

Comments
 (0)