onYouTubeIframeAPIReady() not firing

JGVM picture JGVM · Apr 10, 2014 · Viewed 24.1k times · Source

I've looked through so many questions and the youtube api stuff but for the life of me can't figure out why the onYouTubeIframeAPIReady is not working.

Here is my iframe:

<iframe id="youtube_vid" width="763" height="430" src="https://www.youtube.com/embed/dlJshzOv2cw?theme=light&amp;showinfo=0&amp;rel=0&amp;enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>

And my script:

function callYTapi() {

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

    function onYouTubeIframeAPIReady() {
        console.log('IframeAPI = Ready');
        var player = new YT.Player('youtube_vid', {
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PAUSED) {
            console.log("Paused");
        }

        if (event.data == YT.PlayerState.PLAYING) {
            console.log("Playing");
        }

        if (event.data == YT.PlayerState.ENDED) {
            end(); 
        }
    }
}

I get the console.log for the loaded script but not for Iframe ready or anything else. Any ideas? Thanks

Answer

Vinicius Pinto picture Vinicius Pinto · Apr 10, 2014

The callback functions must be in the global scope. Just move onYouTubeIframeAPIReady and the others outside callYTapi.