YouTube Iframe Api Test

by Adi Jaya

HTML

<div id="player"></div>

<h2 id="h2">Lorem</h2>
<h2>Ipsum</h2>

JavaScript

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: '200',
          width: '300',
          videoId: 'M7lc1UVf-VE',
          playerVars: {
            'playsinline': 1
          },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.player.playVideo();
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
      	console.log( event.data )
        switch(event.data) {
        	case 0:
          	console.log( "video ended" );
            break;
          case 1: 
          	console.log( "video playing" );
            __demoFunction( 10 );
            break;
          case 2:
          	console.log( "video paused" )
        }
      }

			function __demoFunction( sec ){
					var curentTime = player.getCurrentTime();
          var targetTime = sec // on seconds
          var el = document.querySelector( "#h2" );
          if( curentTime > targetTime ){
          		el.textContent = "OK";
          }
      }