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.