Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
    }
});
like image 918
styler Avatar asked Apr 22 '13 10:04

styler


1 Answers

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.

like image 110
Jeff Posnick Avatar answered Sep 20 '22 21:09

Jeff Posnick