Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick slider - Pause a YouTube clip when slider goes to next frame

I’m using slick slider as a multiple gallery slider and one of the items is a YouTube clip. Everything works great, except if a user clicks on the next or previous slide the video keeps playing. I can’t seem to find any documentation on how to automatically pause or stop a YouTube clip when it’s out of frame.

like image 270
Jack Barham Avatar asked Nov 12 '14 17:11

Jack Barham


1 Answers

I'm using slick v1.5.9 and to solve this, I'm currently using jquery .each to loop through all the iframes and ask each of the iframe to stop playing after slick slider's afterChange event was triggered.

How to stop an iframe :

You can refer here to know how to stop/pause an youtube iframe.

Slick Slider's afterChange event :

You can go to slick-slider's github to know more about its events/settings

Below is my codes for reference :

$('.hero-slider').on('init', function(event, slick){
    //init code goes here
}).on('afterChange',function(e,o){
    //on change slide = do action
    $('iframe').each(function(){
        $(this)[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');    
    });
}).slick();

p/s: remember your youtube iframe's parameter's enablejsapi=1 :

<iframe src="https://www.youtube.com/embed/xxxxxx?autoplay=0&enablejsapi=1"></iframe>
like image 129
Mavichow Avatar answered Oct 19 '22 17:10

Mavichow