BXSlider Pause Youtube Video When Switching Slides

Jab018 picture Jab018 · Dec 16, 2014 · Viewed 7.1k times · Source

I have the following example of BXSlider, where I have 4 slides each having a Youtube video. The problem is that when I play a video and go to the next slide, it keeps on playing:

http://jsfiddle.net/isherwood/XWL9Y/

$(document).ready(function () {
$('.bxslider').bxSlider();
});

Can someone help out to make the youtube video pause when going to the next slide?

Answer

Vibhor Dube picture Vibhor Dube · Jan 2, 2015
var slider = $("#gallery").bxSlider({
    adaptiveHeight:true,
    auto:true, 
    autoStart:true, 
    autoControls:true, 
    video:true,
    onSlideAfter: function(slide){
       if (slide.find("iframe:first").length) {
           slider.stopAuto();
       }
    }
});

You might also be able to use something like slide.find("div.fluid-width-video-wrapper:first") if you use iframes for other things in the in the slider.

Source

----Update----

var slider = $('.bxslider').bxSlider({
  onSlideAfter: function(slide, oldindex, currentSlide){
    oldSlide = $( '.bxslider > li:nth-child(' + (oldindex+1) + ')');
      youtubeVideo = oldSlide.find('iframe[src*=youtube]');
      if ( youtubeVideo.length ) {
        youtubeVideo.get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
      }
  }
});

Source

----Edit----

Also make sure to add ?enablejsapi=true to the the iframe src, otherwise the above JavaScript will not work (source).