Can not add dynamically items to Owl Carousel in Javascript

安稳与你 提交于 2019-12-06 11:31:39

There can be two regular errors:

  1. The button does not exist in time you create onclick event.
    • make sure the button exists in time you assign the event.
  2. The carousel is inside the <form> and clicking the button submits the entire form (pay attention at browser page loading). Error shown here.

$(document).ready(function() {
    $("#avatar-carousel").owlCarousel({
        nav: true,
        items: 5
    });

});

$("#click").click(function(e) {
    e.preventDefault(); //-- prevent form submit
    $('#avatar-carousel').trigger('add.owl.carousel', ['<div class="item"><img src="http://placehold.it/140x100" alt=""></div>'])
        .trigger('refresh.owl.carousel');
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>
<form action="" method="post">
    <div id="avatar-carousel" class="owl-carousel">
        <div class="item item-logo">
            <img src="http://placehold.it/140x100" alt="">
        </div>
    </div>
    <button id="click">
        click
    </button>
</form>
Spider

It seems that all answers here work perfectly, but not in my case. Probably the events that are called are in conflict with others. So I did it another way:

Clear the content of the carousel

$('#avatar-carousel').html('');

Append the new content into the carousel

imgs.forEach(function(img) {
  $('#avatar-carousel').append(createImgCarousel(img));
});

Where imgs is an array of image urls, and createImgCarousel a function that creates a carousel item.

Finally reinitialize the carousel

$("#avatar-carousel").owlCarousel({
  navigation: true,
  pagination: true,
  slideSpeed: 1000,
  stopOnHover: true,
  autoPlay: true,
  items: 5,
  itemsDesktopSmall: [1024, 3],
  itemsTablet: [600, 1],
  itemsMobile: [479, 1]
});

It's maybe not so clean, but it works for now !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!