styler
styler

Reputation: 16511

Problems adding youtube iframe code inside document.ready

I want to add the youtube iframe api code inside my $(document).ready() function but when I do this the player doesnt seem to load, when i move the code outside the document.ready the player loads in fine. Can anyone offer me any suggestions on how i can make this video appear when inside the function?

JS

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

    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'u1zgFlCw8Aw',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady() {
        console.log('ready');
    }

    function onPlayerStateChange() {
        console.log('player changed');
    }
});

Upvotes: 7

Views: 2526

Answers (2)

Jeff Posnick
Jeff Posnick

Reputation: 56144

If you change function onYouTubePlayerAPIReady() {...} to window.onYouTubePlayerAPIReady = function() {...} then it's possible to define your YouTube iframe API callback within the $(document).ready() function, and potentially pull in other variables from the $(document).ready() scope into your callback scope.

I'm not sure there's much of an advantage to doing that, though, but it's an option if you really want to.

Upvotes: 11

Tim Vermaelen
Tim Vermaelen

Reputation: 7069

The script will call onYouTubePlayerAPIReady() when it's loaded. When you ... let's say ... "hide" these functions inside your DOM ready wrapper they aren't available anymore for the YT API to call (out of scope).

Because you can't access the YT API script file directly you can't change this behavior and imho what you ask isn't possible.

Upvotes: 0

Related Questions