title: How to Dynamically change Youtube Player videoID
body: <p>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:</p>
  
  <p><strong>html</strong>   </p>
  
  <pre><code>&lt;!-- 1. The &lt;iframe&gt; (and video player) will replace this &lt;div&gt; tag. --&gt;
  &lt;div id="player"&gt;&lt;/div&gt;
  </code></pre>
  
  <p><strong>javascript</strong></p>
  
  <pre><code>// 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 &lt;iframe&gt; (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: '&lt;&lt;CALL TO FUNCTION OR VARIABLE HERE&gt;&gt;',
        events: {
           //'onReady': onPlayerReady,
           'onStateChange': onPlayerStateChange
        }
     });
  }
  </code></pre>
  
  <p>If you are familiar with this code then what happens is the <code>#player</code> DIV is replaced by an IFRAME. I can change the IFRAME source with this function:</p>
  
  <pre><code>function postSelection() {
      $("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Regards.</p>