Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  1] [ 3]  / answers: 1 / hits: 16736  / 7 Years ago, wed, april 19, 2017, 12:00:00

I'm trying to dynamically add items to an Owl carousel. Here is how I'm doing it:



HTML



<div id=avatar-carousel class=owl-carousel lesson-carousel>
<div class=item item-logo>
<div class=product-item>
<div class=carousel-thumb style=height: 77px!important;width: 70px; >
<img src=http://placehold.it/140x100 alt=>
</div>
</div>
</div>
<!-- Start Item -->
</div>

<button id=click>
click
</button>


JS



$(#avatar-carousel).owlCarousel({

items: 5
});

$(#click).click(function(){
$('#avatar-carousel').trigger('add.owl.carousel', ['<div class=item><p>' + 'hh' + '</p></div>'])
.trigger('refresh.owl.carousel');
});


Nothing happens with this code. I can't see the error. Here is the fiddle: JSFiddle.



EDIT:



Seems like the code is correct, as it's working in the fiddle.
I forgot to mention that the carousel works just fine, it is loaded correctly in the beginning. The issue is when trying to add items. Nothing happens, no errors but items are not added.


More From » jquery

 Answers
24

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>




[#58090] Monday, April 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;