Jonathan
Jonathan

Reputation: 1695

Cannot fire "loadVideoByUrl('...')" of Youtube's Iframe-API – undefined

it seems that I am missing something obvious here but I can not get

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";

var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player1');
    // here everything is fine and I can see the 
    // function as part of player
    console.log(player);
    // but here it says "player.loadVideoByUrl()" undefined
    player.loadVideoByUrl("https://youtu.be/bHQqvYy5KYo");
    player.playVideo();
}

to work. Any ideas?

Thanks in advance!

Upvotes: 2

Views: 1383

Answers (1)

st.
st.

Reputation: 589

I assume that player is not initialized while you're calling the loadVideoByUrl function. In documentation, they use

events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }

events of player. It seems player object constructs asynchronously. So if you use those events, code becomes like below:

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";

var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player1', {
      events: {
        'onReady': onPlayerReady
      }
    });
}

function onPlayerReady(){
     player.loadVideoByUrl("https://youtu.be/bHQqvYy5KYo");
     player.playVideo();
}

Upvotes: 3

Related Questions