Skip to content
Advertisement

Load YouTube video and listen to onPlayerStateChange

On clicking a link, I’m trying to play a YouTube video and replace that video with an image when it’s done playing.

The first half was easy. However I’m running into trouble with the second half. Originally I simply appended an iframe embed. However to listen to the ENDED event, I tried to follow the YouTube dev documentation. Now, I cant seem to do anything. Please review. This is what I have thus far.

 var t1 = '<div id="tubewrapper"><div id="player"></div></div>'


$("#link").click( function()
           {
             
             $(".trailers-band").append(t1);


    var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
             var player;
               function onYouTubeIframeAPIReady(){
                   player = new YT.Player('player',{
                       height:'100%',
                       width:'100%',
                       videoId:tubeID,
                       events:{
                           'onReady': onPlayerReady,
                           'onStateChange': onPlayerStateChange
                       }
                   });
               }
            function onPlayerReady(event){
                alert("ready");
                event.target.playVideo();
            }

             var done = false;

             function onPlayerStateChange(event){
                 if (event.data == YT.PlayerState.ENDED && !done){
                     done = true;
                     alert("done");

                 }

             }

           }
        );

Advertisement

Answer

Here is an example of how to play a video, detect when it ends, then display an image in its place.

Example: jsFiddle

<div id="player" style="display:none;"></div>
<a href="#" id="link">play</a>
<script>
// Load API asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: '9vHFsXOdTt0',
        events: {'onStateChange': onPlayerStateChange}
    }); // create the <iframe> (and YouTube player)
}

function onPlayerStateChange(event) {    
    if(event.data === 0) {          
        hideVideo();
    }
}

function hideVideo() {
    var img_url = 'https://www.google.com/images/srpr/logo4w.png';
    $('#player').replaceWith('<img src="'+img_url+'">');
}

$("#link").click(function(){
    $('#player').show(); // show player
    player.playVideo(); // begin playback
});
</script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement