Youtube iFrame embed stopVideo not a function

user3861559 picture user3861559 · Dec 28, 2016 · Viewed 11.9k times · Source

I am trying to embed a youtube iframe in a custom light box I have on my site. The embed itself works fine. The lightbox closes when I attempt to close it but the video (audio rather) keeps play in the background. stopVideo function returns "stopVideo is not a function"

$("#youTubeLink").click(function(){
     var f = '<iframe id="ytplayer" type="text/html" width="100%" height="400px" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>'
     global.addLightboxContent(f);
     global.showLightbox();
});

When I close the lightbox this is what happens

$("div#lightbox-close").click(function() {
    $('#ytplayer').stopVideo();
    global.killLightbox();
}
  • global lightbox functions are doing what they should (add iframe into LB, show it and then kill it)
  • when div#lightbox-close is clicked on, the function is triggered. Tested with a console log

I am guessing I am missing some sort of Youtube js script include. I am not sure what exactly.

Answer

marti_ picture marti_ · Dec 28, 2016
// https://developers.google.com/youtube/iframe_api_reference

// global variable for the player
var player;

// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
  // create the global player from the specific iframe (#video)
  player = new YT.Player('video', {
    events: {
      // call this function when player is ready to use
      'onReady': onPlayerReady
    }
  });
}

function onPlayerReady(event) {

  // bind events
  var playButton = document.getElementById("play-button");
  playButton.addEventListener("click", function() {
    player.playVideo();
  });

  var pauseButton = document.getElementById("pause-button");
  pauseButton.addEventListener("click", function() {
    player.pauseVideo();
  });

}

// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

please check this example http://codepen.io/marti1125/pen/XdyPOe