How to Play a Single Video on a Page With Multiple Youtube Videos

Recently, I had to create a portfolio page with multiple Youtube videos on a single page and the client has some specific requirement. 

At any given time only one video should play & If a video is play and the visitor hits play on a different video, the previous video should pause

Here's the code used to achieve the desired result.

HTML

Add the Youtube iframe script
<script src='https://www.youtube.com/iframe_api?ver=1.0.0'></script>

Setup the div elements where you want the videos.
<div id="player-videoIdA" data-src="videoIdA">Youtube</div>
<div id="player-videoIdB" data-src="videoIdB">Youtube</div>
<div id="player-videoIdC" data-src="videoIdC">Youtube</div>

JS

/*Define a list*/
var ytlist = [
{
id: "player-videoIdA", 
VideoId: "videoIdA"
},{
id: "player-videoIdB", 
VideoId: "videoIdB"
},{
id: "player-videoIdC", 
VideoId: "videoIdC"
}
];

var players = [];
function onYouTubePlayerAPIReady() {
for(i = 0; i < ytlist.length; i )
{
  players[i] = createVideo(ytlist[i]);
  jQuery("#" ytlist[i].id).empty();
}
}


function createVideo(vid){
return new YT.Player(vid.id, {
    height: '400',
    width: '600',
    videoId: vid.VideoId,
    playerVars: {rel: 0, showinfo: 0, ecver: 2},
    enablejsapi:1,
    modestbranding:1,
    events: {
      onStateChange: onPlayerStateChange
    }
  });
}

function onPlayerStateChange(event) {
/* if video is loading or playing */
if(event.data == -1 || event.data == 1)
  {
    var curr = event.target.f;
    var data = jQuery(curr).attr('id');
    var dx = data.split("-");
    /*pause all videos*/
    for(i = 0; i < ytlist.length; i )
      {
      if(jQuery(players[i].f).attr('id') != data)
        {
          players[i].pauseVideo();
        }
    }
  }
}