Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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>

Post a Comment for "Load YouTube Video And Listen To OnPlayerStateChange"