How to Dynamically change Youtube Player videoID

Serious Starsider picture Serious Starsider · Nov 1, 2012 · Viewed 45k times · Source

I want to use the YT.Player code so that I can detect events. I have a CSV file with Youtube video ID's and a function that puts the ID's in an array and want to be able to dynamically change the ID when a user click an image. Essentially like this:

html

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

javascript

// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
// NOTE: videoId is taken out and instead is placed as the generated IFRAME src from the postSelection function

var player;
function onYouTubeIframeAPIReady() {
   player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      videoId: '<<CALL TO FUNCTION OR VARIABLE HERE>>',
      events: {
         //'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
      }
   });
}

If you are familiar with this code then what happens is the #player DIV is replaced by an IFRAME. I can change the IFRAME source with this function:

function postSelection() {
    $("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file
}

But this is very buggy and not cross browser friendly. If I use a standard IFRAME and not the YT Player API then everything works just fine. But I want to detect the end, and pause and so on so I have to use the API. My guess is that it is an issue with state and that persistence is lost some where in the creation of the IFRAME.

Regards.

Answer

Greg Schechter picture Greg Schechter · Nov 1, 2012

This is very simple to do with the js api. When you want to load a new video just call player.loadVideoById(videoId); Details at https://developers.google.com/youtube/iframe_api_reference#loadVideoById