Mpak91 Mpak91 - 4 months ago 143
Javascript Question

Owl Carousel 2 dynamically add videos

I'm trying dynamically add Owl Carousel videos to my site, but I ran into a problem; Videos appear on the page but when I try to play them console says

TypeError: video is undefined
width = video.width || '100%'


I've tried to follow instructions found on Owl Carousel documentation http://www.owlgraphic.com/owlcarousel/demos/manipulations.html and some posts here on StackOverFlow, but can't figure this out. There are not many, if any, documentation about how to dynamically add videos in Owl Carousel.

My current code is following:

<script>
//init carousel
var owl = $('.owl-carousel');
$(document).ready(function(){
owl.owlCarousel({
touchDrag: true,
startPosition: 1,
merge:true,
margin:10,
video:true,
center:true,
responsive:{
320:{
items:1
},
900:{
items:3
}
}
});

var html = `<div data-merge="1" class="item-video">
<div class="owl-video-wrapper">
<a class="owl-video" href="https://www.youtube.com/watch?v=dOWFVKb2JqM" style="display: none;"></a>
<div class="owl-video-play-icon"></div>
<div class="owl-video-tn" style="opacity:1;background-image:url(http://img.youtube.com/vi/dOWFVKb2JqM/hqdefault.jpg)"></div>
</div>
</div>`;
var content = '<div class="owl-item" data-video="https://www.youtube.com/watch?v=dOWFVKb2JqM">'+html+'</div>';
owl.trigger('add.owl.carousel', [$(content), 0]).trigger('refresh.owl.carousel');
});
</script>


I also tried to add them like this:

var content = `<div class="item-video" data-merge="1"><a class="owl-video" href="https://www.youtube.com/watch?v=JpxsRwnRwCQ"></a></div>`;
owl.trigger('add.owl.carousel', [$(content), 0]).trigger('refresh.owl.carousel');


My idea is later on to fetch video URLs from Ghost CMS API and initiate Owl Carousel videos with this data. Help on this highly appreciated!

Answer

I got it working by using different approach; dynamically add videos as iframe-embeds.

This is what I got now and everything working. lazyYT is jQuery-plugin for lazy-loading youtube-videos. https://github.com/tylerpearson/lazyYT

var content = `<div data-merge="1" class="item-video"> <div class="lazyYT" data-youtube-id="`+parsedUrl+`" data-ratio="16:9"></div></div>` // Add video to carousel owl.trigger('add.owl.carousel', [$(content), 0]).trigger('refresh.owl.carousel').trigger('to.owl.carousel', 1);

Just wanted to let you know and maybe its useful for somebody. :)

Comments