Attempt of iframe YouTube

For continue looping the iframe. This is an attempt to answer this question: https://stackoverflow.com/q/54350355/4092887

by MauricioSOes

HTML

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

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);

// Variables of the divs (where the YouTube iframe will load):
var player;

function onYouTubeIframeAPIReady() {

  // Div player:
  player = new YT.Player('player', {
    height: '360',
    width: '640',
    videoId: 'xPCZEoGJi_4',
    playerVars: {
      'autoplay': 1,
      'loop': 1,
      'mute': 1
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

}

// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {

  // When the video ends, it will play again.
  // See: https://developers.google.com/youtube/iframe_api_reference?hl=en#Events
  if (event.data == YT.PlayerState.ENDED) {
    player.playVideo();
  }
}

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