Adding pause/play button to Bootstrap carousel for better accessibility.

Starting with the example code for a carousel with indicators we add another button to the beginning of .carousel-indicators.

<button type="button" class="btn btn-sm" id="carouselExamplePause" aria-label="Pause">&#x23F8;&#xFE0E;</button>

Then we add JavaScript to make it functional.

document.addEventListener('DOMContentLoaded', () => {
    const element = document.getElementById('carouselExampleIndicators')
    const carousel = new bootstrap.Carousel(element)
    const button = document.getElementById('carouselExamplePause')
    
    button.addEventListener('click', (event) => {
        if (event.isTrusted) {
            carousel[carousel._interval ? 'pause' : 'cycle']()
        }
        
        if (carousel._interval) {
            button.innerHTML = '&#x23F8;&#xFE0E;'  // ⏸︎
            button.ariaLabel = 'Pause'
        } else {
            button.innerHTML = '&#x23F5;&#xFE0E;', // ⏵︎
            button.ariaLabel = 'Play'
        }
    })
    
    element.addEventListener('slide.bs.carousel', (event) => {
        if (carousel._config.ride && !carousel._interval) {
            carousel._interval = true
        }
        
        button.dispatchEvent(new Event('click'))
    })
    
    button.dispatchEvent(new Event('click'))
})

Once we have the carousel instance and button we can pause/cycle when triggered by user interaction (eg: isTrusted). Then we update the button state (eg: paused when carousel_interval is null). We also set _interval to true in the slide event when ride is not set to true/carousel to ensure the correct button state is displayed.

Note: We encountered multiple sources claiming there was no “is playing” property for carousels. We determined _interval can serve that purpose based on pause() and cycle().

Leave a Reply

Your email address will not be published. Required fields are marked *