Owlcarousel 2 dynamically loaded content

Arkadiusz Rosiak picture Arkadiusz Rosiak · Aug 19, 2014 · Viewed 21k times · Source

I have troubles with ajax loading content to owl carousel 2. I'm trying to get new items by this function:

function loadDecisions(pageNumber) {
   $.ajax({
       url: globalURL,
       type: 'POST',
       data: {
           action: 'lw_infinite_scroll',
           loop_file: 'video',
           page_no: pageNumber,
           posts_per_page: postsPerPage
       },
       success: function(data) {
           $(".owl-stage").append(data);    
           owl = jQuery('.owl-carousel');

           count++;
           resizeStage();
       },
       error: function(e) {
       }
   });
   return false;
}

If I append new items to .owl-stage like this $(".owl-stage").append(data); I can see them, but I can't slide to them. I think owlcarousel think that there still are only 5 items, even if i added much more.

The situation changes if i change $(".owl-stage").append(data); to $(".owl-stage").html(data);. Then obviously old content disapears, but I can slide to new items.

Can anyone suggest what I should do? I'm using owlcarousel 2.0.4.

Answer

Alex C picture Alex C · Oct 28, 2016

For me the accepted answer did not work, but this solution did the job:

$('.owl-carousel').owlCarousel().trigger('add.owl.carousel', 
                  [jQuery('<div class="owl-item">' + html +
                          '</div>')]).trigger('refresh.owl.carousel');

This because, at least on the Owl Carousel v2 of today needs a jQuery object to be passed to "add".

See Github ticket #1170 where Gurunave explains this best.