Skip to main content

Command Palette

Search for a command to run...

How to sync two owl carousels ?

Updated
1 min read
How to sync two owl carousels ?
S
I write code, deploy code, and fix the infrastructure when it cries...

The best and the perfect code you'll require to sync two owl carousels so that it slides together. Check the code below

  $(document).ready(function () {
    // Initialize the first carousel
    var owl1 = $('#owl-carousel1').owlCarousel();

    // Initialize the second carousel
    var owl2 = $('#owl-carousel2').owlCarousel();

    // Flag to prevent recursive calls
    var changingFromOwl1 = false;
    var changingFromOwl2 = false;

    // Event listener for owl-carousel1 changes
    owl1.on('change.owl.carousel', function (event) {
      if (!changingFromOwl2 && event.namespace && event.property.name === 'position') {
        changingFromOwl1 = true;
        var target = event.relatedTarget.relative(event.property.value, true);
        owl2.owlCarousel('to', target, 300, true);
        changingFromOwl1 = false;
      }
    });

    // Event listener for owl-carousel2 changes
    owl2.on('change.owl.carousel', function (event) {
      if (!changingFromOwl1 && event.namespace && event.property.name === 'position') {
        changingFromOwl2 = true;
        var target = event.relatedTarget.relative(event.property.value, true);
        owl1.owlCarousel('to', target, 300, true);
        changingFromOwl2 = false;
      }
    });
  });

More from this blog

Cloud Code Chronicles

48 posts

An enthusiast of Development, Cloud & DevOps