Adrian Neatu
Adrian Neatu

Reputation: 2039

Listen when youtube player is embedded

Is there a way to know when youtube player was successfully embedded ? I'm using the iframe embedding and I would like to do some actions after the player has loaded.

Upvotes: 0

Views: 114

Answers (1)

jlmcdonald
jlmcdonald

Reputation: 13667

I'm assuming you're talking about including the iFrame embed code itself, rather than using javascript to embed it? (Either way, it's not much different.) For that, you'll want to use the YouTube iFrame javascript library so you can bind to the iFrame and know its status.

To load the library, use this code:

var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

When the iFrame javascript library is successfully injected, it will call onYouTubeIframeAPIReady, so if you define that function you can know when the iFrame binding support is ready to go. Within that function, then, you'll want to set up a YT.Player object for your iframe:

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', { // the first argument is the id of your iframe
      events: {
        'onReady': onPlayerReady
      }
    });
  }

The onReady callback is bound to a function here named onPlayerReady, so the final step would be to just define that function:

function onPlayerReady() {
     alert('iframe is embedded and player is loaded!');
}

Here's a jsfiddle to demonstrate.

Upvotes: 1

Related Questions