How do I attach a jQuery event handler to a YouTube movie?
flash, javascript, jquery, jquery-events, jquery-plugins
Solution
The YouTube player API is pretty straight-forward. You just have to listen to the `onStateChange` event and control the cycle plugin depending on the state:
Here's a working demo: http://jsbin.com/izolo (Editable via http://jsbin.com/izolo/edit)
And the pertinent code:
function handlePlayerStateChange (state) {
switch (state) {
case 1:
case 3:
// Video has begun playing/buffering
videoContainer.cycle('pause');
break;
case 2:
case 0:
// Video has been paused/ended
videoContainer.cycle('resume');
break;
}
}
function onYouTubePlayerReady(id){
var player = $('#' + id)[0];
if (player.addEventListener) {
player.addEventListener('onStateChange', 'handlePlayerStateChange');
}
else {
player.attachEvent('onStateChange', 'handlePlayerStateChange');
}
}
Problem
[EDIT: Sorry to those who already answered -- in my sleep-deprived state, I forgot that this particular situation is a YouTube movie, not the JW FLV player. I can see that there is more extensive documentation on interacting with YouTube movies, so I will pursue that, but any more information is also welcome] I am using embedded YouTube videos in a collection of divs that are being rotated by using the jQuery cycle plugin (http://malsup.com/jquery/cycle/). I would like the cycle to stop when I click on one of the movies to start it playing, but I can't figure out how to attach a jQuery event handler to the player object. Here's what my current code looks like (you can't directly select an object tag with jQuery, so I select the parent div and then get the object element as the first child): ``` $("div.feature-player").children(":first").click(function(event) { $('#features').cycle('stop'); }); ``` But that doesn't do the trick. I'm not a Flash author, so I'm not really familiar with ActionScript, and I've never set up an interaction between JavaScript and a Flash movie before.