I'm currently trying to use the YouTube API as part of a jQuery plugin and I've run into a bit of a problem.

The way the YT api works is that you load the flash player and, when it's ready it will send a call back to a global function called onYouTubePlayerReady(playerId). You can then use that id combined with getElementById(playerId) to send javascript calls into the flash player (ie, player.playVideo();).

You can attach an event listener to the player with player.addEventListener('onStateChange', 'playerState'); which will send any state changes to another global function (in this case playerState).

The problem is I'm not sure how to associate a state change with a specific player. My jQuery plugin can happily attach more than one video to a selector and attach events to each one, but the moment a state actually changes I lose track of which player it happened in.

I'm hoping some example code may make things a little clearer. The below code should work fine in any html file.

5 Answers
5

Apparently calling addEventListener on the player object causes the script to be used as a string in an XML property that's passed to the flash object - this rules out closures and the like, so it's time for an old-school ugly hack:

"onYouTubePlayerReady must be outside of $(document).ready(function() to get fired" -- you saved my life
–
MustafaAug 12 '11 at 20:45

4

One small note: the onYouTubePlayerReady() function code can be within the $(document).ready, but it must be scoped to the window/global object outside of jQuery, so the function would instead need to be defined as such: window.onYouTubePlayerReady(playerId) {}
–
TimKlimowiczMar 30 '12 at 18:30

Here's a nice article that goes through creating a class to wrap an individual player, including dispatching events to individual objects using a similar approach to that mentioned in a previous answer.