Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Youtube iframes in Bootstrap Carousel - stop video on slide

I have a bunch of Carousels on a page, each with a mix of videos and images. I'd like to stop Youtube videos from playing when the user exits a video by clicking one of the carousel controls (left or right).

I'd like to be able to detect when the user clicks the controls, create a player based on the current video that was playing, and turn that video off. In the other examples I've seen, the players were declared in the onYoutubeIframeAPIReady function, but I thought it would be better not to dynamically create players for every video on the page. Right now, I'm getting the error

Uncaught TypeError: Object #<T> has no method 'stopVideo' 

when I click the carousel controls. However, if I type

player.stopVideo();

in the Chrome javascript console, it works fine. What am I doing wrong?

  <script>
  var youtubeReady = false;

  function onYouTubeIframeAPIReady(){
    youtubeReady = true;
  }

  $('.carousel').on('slide', function(){
    if(youtubeReady){
      console.log("setting player");
      var iframeID = $(this).find('.active').find('iframe').attr("id");
      player = new YT.Player(iframeID); 
      player.stopVideo(); 
    }
  });
  </script>

Example carousel:

<div class="mainPhoto carousel slide 523" id="carousel-523">
          <div class="carousel-inner 523">
          <div class="item active">
             <div class="flex-video">
                 <a class="fancybox" href="http://www.youtube.com/embed/4pEqbs0ISaw?version=3&amp;enablejsapi=1" rel="gallery 523" data-fancybox-type="iframe">
                     <iframe src="http://www.youtube.com/embed/4pEqbs0ISaw?version=3&amp;enablejsapi=1" id="1188">
                     </iframe>
                 </a>
             </div>
         </div>
        <div class="item">
             <a class="fancybox" href="https://buildinprogress.s3.amazonaws.com/image/image_path/1189/2013-07-05_19.47.55.jpg" rel="gallery 523" data-fancybox-type="image">
                 <img alt="Preview_2013-07-05_19.47.55" id="1189" src="https://buildinprogress.s3.amazonaws.com/image/image_path/1189/preview_2013-07-05_19.47.55.jpg" width="100%">
            </a>
        </div>
    </div>
            <a class="carousel-control left" href="#carousel-523" data-slide="prev" style="display: none;">‹</a>
            <a class="carousel-control right" href="#carousel-523" data-slide="next" style="display: none;">›</a>
        </div>
like image 833
scientiffic Avatar asked Oct 22 '22 06:10

scientiffic


1 Answers

I ended up using the callPlayer function here (which didn't require using the youtube API at all):

YouTube iframe API: how do I control a iframe player that's already in the HTML?

like image 184
scientiffic Avatar answered Oct 24 '22 04:10

scientiffic