Bootstrap carousel: How to slide two carousel sliders at a same time?

Viewed 16076

I have three carousel sliders on the single page and I want them to move two of them at the same time .i.e. both should change slider images at the same time. Both have same number of images/slides. Here is the code I am using:

jQuery('#carousel-example-generic1, #carousel-example-generic2').carousel({
    interval: 4000
});

And also I tried this code below:

jQuery('.carousel').carousel({
    pause:'false'
});

jQuery('#carousel-example-generic1').on('slide', function(){
    jQuery('#carousel-example-generic2').carousel('next');
});

But left and right sliders have very little delay in changing slides. And this delay goes on increasing. Any known issues with this kind of problem? Link to the site is this.

JSFiddle: Link

5 Answers

Since the answer of @zessx does not work properly anymore after changing slides by using the carousel-indicators, I want to provide an extended answer based on his option #2. This extended answer will also sync slide changes triggered by clicks on carousel-indicators:

$('.carousel-sync').on('slide.bs.carousel', function (ev) {
    // get the direction, based on the event which occurs
    var dir = ev.direction == 'right' ? 'prev' : 'next';
    // get synchronized non-sliding carousels, and make'em sliding
    $('.carousel-sync').not('.sliding').addClass('sliding').carousel(dir);
});
$('.carousel-sync').on('slid.bs.carousel', function (ev) {
    // remove .sliding class, to allow the next move
    $('.carousel-sync').removeClass('sliding');
});

// sync clicks on carousel-indicators as well
$('.carousel-indicators li').click(function (e) {
    e.stopPropagation();
    var goTo = $(this).data('slide-to');
    $('.carousel-sync').not('.sliding').addClass('sliding').carousel(goTo);
});

Please note that this requires the synced carousels to have the same number of slides. If it is not the case, you have to add a fallback for those cases where "goTo" does not exist for all synced carousels.

If you are using Twitter Bootstrap 3 (didn't check with 4). You can use classes instead of id's.

<div id="carousel-a" class="carousel slide carousel-sync" >
  ...
</div>

<div id="carousel-b" class="carousel slide carousel-sync" >
  ...
</div>

In the above case carousel-sync. Then in the controls you just use href=".carousel-sync". And it will work in all directions.

if you are using the latest bootstrap 4 or 5.

$('.carousel-1').on('slide.bs.carousel', function(ev) {
  $('.carousel-2').carousel(ev.to);
});
Related