passatgt
passatgt

Reputation: 4442

onYouTubePlayerReady is not firing when the page is loaded with ajax

I have the following jQuery script that loads a page with ajax, and i want to display a video using the Youtube API when the page is loaded:

$("#games_slides").load($(this).attr('href'), function(){
    function onYouTubePlayerReady(playerId) {
            ytplayer = document.getElementById("ytPlayer");
            ytplayer.cueVideoById("ylLzyHk54Z0");
            ytplayer.playVideo();
    }

    function loadPlayer() {
            var params = { allowScriptAccess: "always" };
            var atts = { id: "ytPlayer" };
            swfobject.embedSWF("http://www.youtube.com/apiplayer?" + "version=3&enablejsapi=1&playerapiid=player1", "youtubePlayer", "480", "295", "9", null, null, params, atts);
    }

    loadPlayer();
});    

The player is loaded, so the loadPlayer functions is working, but the onYouTubePlayerReady function is not firing. Any idea why?

Upvotes: 0

Views: 3111

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56144

The onYouTubePlayerReady function needs to be in the window context (so that the ActionScript code can call it after it's loaded), and your definition of the function appears to have some local context.

Try

window.onYouTubePlayerReady = function(playerId) {
  ytplayer = document.getElementById("ytPlayer");
  ytplayer.cueVideoById("ylLzyHk54Z0");
  ytplayer.playVideo();
}

Upvotes: 13

Related Questions