Search code examples
javascriptjquerycarouselowl-carousel-2

Update owl Carousel number of items


I've added Owl carousel to a page. I want to update number of items after ajax call. I tried this but it's not working on my end.

jQuery('.owl-carousel').owlCarousel({
  items: 4,
  responsive: {
    0: {
      items: 1,
      nav: true
    },
    640: {
      items: 2,
      nav: true
    },
    1025: {
      items: 4,
      nav: true
    }
  }
});

jQuery('.owl-carousel').trigger('initialize.owl.carousel');
jQuery('.owl-carousel').trigger('refresh.owl.carousel');

Solution

  • I don't get the impression that Owl Carousel has a function to detect and add slides. You can add and remove them manually, but not automatically.

    You probably want to destroy and rebuild:

    ...trigger('destroy.owl.carousel');
    ...owlCarousel({...});
    

    You could detect the current slide before rebuild and reapply it on rebuild, though it might not match depending on how the data have changed.

    Protip: Save yourself some typing and use this shorthand with alias as your document.ready wrapper. Then you can use $ instead of jQuery in your script statements.

    jQuery(function($) {
        // your script, e.g. 
        // $('.owl-carousel').trigger();
    });