I need to apply an owl carousel and all of it's CSS to dynamic HTML elements coming from an ajax call.
Currently, the code looks like this:
jQuery(function ($) {
$('.entry-content').addClass('entry-content--quiz')
$('.get-questions').on('click', function (e) {
e.preventDefault();
let url = $(this).attr('href');
$.ajax({
url: url,
}).done(function (data) {
$('.entry-content').html(data);
$('#wpvq-page-0').owlCarousel({
items:1,
slideBy: 1,
stagePadding: 0,
nav: true,
dots: false,
});
}).fail(function (err) {
console.log('ajax err back', err);
});
return false;
});
});
This obviously does not work and throws "owl carousel is not a function" because it's not in the DOM on initial load. I need to somehow apply the carousel to a div that comes from data
.
I found some relevant answers but they're not in the context of my situation:
Load dynamic content in Owl Carousel 2
How to re-render a owl-carousel item?
They look like they re-write the DOM but it doesn't make sense in the context of what I'm doing.
How do I put an owl carousel on a div inside HTML that comes from an ajax call?
EDIT 12/10/2018 FULL sample:
jQuery(function ($) {
$('#link').on('click', function (e) {
e.preventDefault();
let url = $(this).attr('href');
$.ajax({
url: url,
}).done(function (data) {
$('#content').html(data);
$('#carousel-section').addClass("owl-carousel");
setTimeout(function() {
$('#carousel-section').owlCarousel({
items:1,
slideBy: 1,
stagePadding: 0,
nav: true,
dots: false,
});
},1000)
}).fail(function (err) {
console.log('ajax err back', err);
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css">
<div id="content"></div>
<a id="link" href="http://silly-stallman-3e4b6f.netlify.com/index.html">Cclick</a>
I can't get the HTML to populate inside the DIV idk why it doesn't work but this is the example of what I'm doing - getting static HTML (http://silly-stallman-3e4b6f.netlify.com/index.html) and putting it into an ajax call, populating the page with it then needing to target the owl carousel to the dynamic HTML somehow. How do I do this?