2

I need to load the youtube iframe player with api on a jquery change event but it only shows how to load it when the script is loaded.

This is the script they use to load the player with the api.

  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.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'u1zgFlCw8Aw',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

I need to wait to fire this until my change event is fired so inside this..

 $(document).on("change","#yt-url", function() {
     youtubeUrl = $(this).val();
     youtubeId = youtube_parser(youtubeUrl);
     // Load the youtube player with api
 });

What's the correct way to do this?

2 Answers 2

4

I think you'd just need to encapsulate the code creating the player into a function, which is called only by given event

$(document).on("change","#yt-url", function() {
    var tag = document.createElement('script');
    tag.src = "//www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
Sign up to request clarification or add additional context in comments.

Comments

3

Dmitry's example works, but I've got two modifications. First, check to see if the API is already loaded (whether YT.Player is defined) and only load the API if it isn't. Second, you might as well use $.getScript() since you mentioned you're using jQuery.

There's an example of this approach at https://code.google.com/p/youtube-direct-lite/source/browse/static/js/ytdl/player.js

1 Comment

Nice example, you should add the code to your answer in addition to the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.