0

I am trying to use the YouTube iframe API to fire an event after a video is finishing playing. The iframe containing the YouTube video is loaded with the document and has the enablejsapi=1 parameter in the URL like so:

<iframe id="myytplayer" src="http://www.youtube.com/v/8mmd_eHYmMY?enablejsapi=1&playerapiid=ytplayer&version=3" allowfullscreen="" frameborder="0"></iframe>

I have successfully implemented the onYouTubeIframeAPIReady function but I cannot add an event listener to the YouTube object once it is ready. The player state alert does not show when playing/pausing the video. Here is my javascript code:

function onytplayerStateChange(newState) {
    alert("Player's new state: " + newState);
    // check player ended
}
function onYouTubeIframeAPIReady() {
    alert("ready");
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", onytplayerStateChange);
}

I also had to load the following resource in order to get the "ready" alert to show up.

<script src="http://www.youtube.com/player_api" type="text/javascript"></script>

I have created a jsFiddle here.

phpete
  • 318
  • 3
  • 12
  • see here, its probably the solution: http://stackoverflow.com/questions/17078094/youtube-iframe-player-api-onstatechange-not-firing – sjkm May 22 '14 at 17:58

1 Answers1

0

You can't add an event listener just to the DOM element (as you could do in the older javascript API); with the iframe API you have to create a YT.player object based on the DOM element first, and then add the event listener there. Something like this:

function onYouTubeIframeAPIReady() {
    ytplayer = YT.Player("myytplayer", {
    events: {
      'onStateChange': onPlayerStateChange
    }
}

Also, be a bit careful loading the player_api via a script tag ... there's no guarantee that your onYouTubeIframeAPIReady function will be defined when that's fully loaded. Better to do something like this, before defining your ready function:

<script>
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
jlmcdonald
  • 13,408
  • 2
  • 54
  • 64