How to add play/pause button for (multiple) two different bootstrap 5 carousels

I have looked at other examples on stack overflow, trying to add these carousel controls and I am able to use one of the carousel controls on my page, but then the other set of controls will not work.

This is what I currently have.

        $(function() {
            $('#keynoteSpeakersCarouselPlayButton').click(function() {
                $(this).closest('.carousel').carousel('cycle');
            });
            $('#keynoteSpeakersCarouselPauseButton').click(function() {
                $(this).closest('.carousel').carousel('pause');
            });
            $('#sponsoredStreamsCarouselPlayButton').click(function() {
                $(this).closest('.carousel').carousel('cycle');
            });
            $('#sponsoredStreamsCarouselPauseButton').click(function() {
                $(this).closest('.carousel').carousel('pause');
            });
        }); 

I would think the solution would not work with jQuery

1 answer

  • answered 2022-04-29 18:30 Mifo

    From my understanding of the bootstrap carousel a method will be ignored if it is in the middle of a transition. You need to add an event listener and do your pause inside of that. I would set a flag, check for it inside of the event listener and then reset the flag. Also I would add IDs to each carousel to make it more straight forward to select. Something like what follows:

    let flagPause = false;
    let flagResume = false;
    
    const carousel1 = document.getElementById('carousel1id');
    carousel1.addEventListener('slid.bs.carousel', function() {
        if (flagPause == true) {
            carousel1.carousel('pause');
            flagPause = false;
        }
        if (flagResume == true) {
            carousel1.carousel('cycle');
            flagResume = false;
        }
    });
    $('#keynoteSpeakersCarouselPlayButton').click(function() {
        flagResume = true;
    });
    $('#keynoteSpeakersCarouselPauseButton').click(function() {
       flagPause = true;
    });
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum