YouTube Video - Player using Nice JS Class

by Ben Clayton

HTML

<script src="https://www.youtube.com/iframe_api"></script>
<!-- YT library included https://www.youtube.com/iframe_api -->
<!-- The <iframe> (and video players) will replace these <div> tags. -->
<div class="myplayer0"></div>
<div class="myplayer1"></div>

<hr>The first parameter specifies either the DOM element or the id of the HTML element where the API will insert the
iframe tag containing the player. The IFrame API will replace the specified element with the
  iframe element containing the player. This could affect the layout of your page if the element being replaced has a different display style than the inserted
    iframe element. By default, an
      iframe displays as an inline-block element. The second parameter is an object that specifies player options. The object contains the following properties: width (number) – The width of the video player. The default value is 640. height (number) – The height
        of the video player. The default value is 390. videoId (string) – The YouTube video ID that identifies the video that the player will load. playerVars (object) – The object's properties identify player parameters that can be used to customize
        the player. events (object) – The object's properties identify the events that the API fires and the functions (event listeners) that the API will call when those events occur. In the example, the constructor indicates that the onPlayerReady function
        will execute when the onReady event fires and that the onPlayerStateChange function will execute when the onStateChange event fires.

JavaScript

class holoVideo {
  constructor(eljselector, videoid) {
    // https://developers.google.com/youtube/iframe_api_reference
    debugger;
    var el = $(eljselector).get(0);
    this.player = new YT.Player( el, {
      height: '10',
      width: '10',
      videoId: videoid,
      playerVars: { // https://developers.google.com/youtube/player_parameters?playerVersion=HTML5
        autoplay: 1
      },
      events: {
        'onReady': function(event) {
          this.onPlayerReady(event)
        }.bind(this),
        'onStateChange': function(event) {
          this.onPlayerStateChange(event)
        }.bind(this)
      }
    });
  }

  onPlayerReady(event) {
    // event.target.playVideo();
    // OR this.player.playVideo()
    this.player.setSize(400, 300);
  }
  onPlayerStateChange(event) {
  	// https://developers.google.com/youtube/iframe_api_reference#Events
    console.log("YT Event fired ",event)
  }
}




function onYouTubeIframeAPIReady() {
  new holoVideo(".myplayer0", 'M7lc1UVf-VE');
  new holoVideo(".myplayer1", '8qeCMLJRQNo');
}