user479947
user479947

Reputation:

Adding JS Youtube API videos programmatically

I'd like to do something like:

// create youtube player
var player = new YT.Player('player', {
  height: '390',
  width: '640',
  videoId: '0Bmhjf0rKe8'
});

var newVideo = $('<div></div>').html(player);
$('body').append(newVideo)

How can I add YouTube video elements programmatically?

Upvotes: 0

Views: 225

Answers (1)

jlmcdonald
jlmcdonald

Reputation: 13667

The YT.Player function takes for its first argument the ID of the element where it is creating the player object; hence, in your code, since you haven't created the element yet, it can't create the iframe or the injected player code. If you reverse your order, though, and give your programmatically created an ID, it should work. You'll also want to put the creation of your players in the onYouTubeIframeAPIReady() callback function, since that will automatically be called when the javascript API is loaded (you can put the creation of multiple players in that one function):

      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      $('body').append("<div id='player1'></div><div id='player2'></div>");
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player1', {
          height: '390',
          width: '640',
          videoId: '0Bmhjf0rKe8'
         }); // repeat for player2, etc.
      }

If you are creating the new YouTube player instances later (when you're sure the API library is already present) such as in response to an event, it won't have to be wrapped in the callback function like that (and of course you won't have to load the javascript itself), but the element where the iframe is to be created will still need to exist in the DOM before calling YT.Player().

Upvotes: 0

Related Questions