Slick-carousel - How To Pause and Play embedded Yo

2019-08-04 06:42发布

问题:

I want to create a Slick slider with Youtube videos, So I can use youtube iFrame embed code directly to slides, and it will work, But what I want to achieve is When the slide changes Video should stop/pause playing.

I am using Slick Slider.

Here Is the HTML I am Using::

<div class="entry_slider_video">
     <div data-thumb="http://placehold.it/140x100">
     <iframe width="560" height="315" src="https://www.youtube.com/embed/gLJdzky63BA" frameborder="0" allowfullscreen></iframe>
     </div>
     <div data-thumb="http://placehold.it/140x100"><iframe width="420" height="315"  src="https://www.youtube.com/embed/Tf4sa0BVJVw?rel=0&amp;enablejsapi=1" frameborder="0" allowfullscreen></iframe>
     </div>
<div data-thumb="http://placehold.it/140x100">
    <iframe width="420" height="315"src="https://www.youtube.com/embed/QF903RaKLvs?rel=0&amp;enablejsapi=1" frameborder="0" allowfullscreen>
   </iframe>
  </div>

And the JS:::

$('.entry_slider_video').slick({
              arrows: false,
              fade: true,
              autoplay: true,
              dots: true,
              customPaging : function(slider, i) {
                  var thumb = $(slider.$slides[i]).data('thumb');
                  return '<a class="enty_thumbs"><img src="'+thumb+'"></a>';
                }
 });

I know I have to use Youtube API(https://developers.google.com/youtube/iframe_api_reference) inorder achieve this, I have tried some of the solutions from SO, but no luck. any help will be appreciated, thank you.

回答1:

You should use the beforeChange event of Slick and send a postMessage to the contentWindow of the iframe. In Code this could look like:

$('.entry_slider_video').on('beforeChange', function(event, slick, currentSlide, nextSlide){
    var data = {"event":"command","func":"pauseVideo","args":""};
    var message = JSON.stringify(data);
    $("iframe", slick.$slides[currentSlide])[0].contentWindow.postMessage(message, '*');
});

Don't forget to add the parameter enablejsapi=1 to the url of the video. The first video in your example doesn't have it.