article

Thursday, November 20, 2014

How to detect when a youtube video finishes playing using javascript

How to detect when a youtube video finishes playing using javascript


 
<div id="player"></div>
    <script src="http://www.youtube.com/player_api"></script>
    <script>
        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              height: '390',
              width: '640',
              videoId: '0Bmhjf0rKe8',
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
        }
        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }
        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }
    </script>

Related Post