I am using http://kenwheeler.github.io/slick/ for the carousal. But the problem is the autoplay slides the slick to next even when the youtube video is playing.
JSFIDDLE
Currently I am using the below JS but nothing seems to work on it.
$('#main-slider').slick({
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000,
dots: true,
infinite: true,
adaptiveHeight: true,
arrows: false
});
var video = $('#main-slider .slick-active').find('iframe').get(0).play();
$('#main-slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
$('#main-slider .slick-slide').find('video').get(0).pause();
var video = $('#main-slider .slick-active').find('video').get(0).play();
});
There are few similar question but none of them has a solution. Slick-carousel how to stop autoplay when video is on via youtube api
Please find the solution here:
Fiddle : http://jsfiddle.net/rijokpaul/pyzpg7st/2/
I solved it with YouTube Iframe API
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
var elems1 = document.getElementsByClassName('yt-player');
for(var i = 0; i < elems1.length; i++) {
player = new YT.Player(elems1[i], {
events: {
//'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}
function onPlayerReady(event) {
}
function handleVideo(playerStatus) {
if (playerStatus == -1) {
// unstarted
$('#main-slider').slick('slickPause');
} else if (playerStatus == 0) {
// ended
$('#main-slider').slick('slickPlay');
} else if (playerStatus == 1) {
// playing = green
$('#main-slider').slick('slickPause');
} else if (playerStatus == 2) {
// paused = red
$('#main-slider').slick('slickPlay');
} else if (playerStatus == 3) {
// buffering = purple
} else if (playerStatus == 5) {
// video cued
}
}
function onPlayerStateChange(event) {
handleVideo(event.data);
}
$(function() {
$('#main-slider').slick({
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000,
pauseOnFocus: false,
pauseOnHover: false,
dots: true,
infinite: true,
adaptiveHeight: true,
arrows: false
});
});
$('#main-slider').on('beforeChange', function(event, slick, currentSlide, nextSlide){
$('.yt-player').each(function(){
this.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*')
});
});
Also updated iframe like the following
<iframe class="yt-player" src="https://www.youtube.com/embed/lqj-QNYsZFk?controls=1&rel=0&enablejsapi=1"></iframe>
Added &enablejsapi=1
at the end of iframe url and used a class called yt-player
.
UPDATE
Commented onReady
function and used slick
beforeChange
event to pause YouTube video when it is not active.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With