How do I attach a jQuery event handler to a YouTube movie?

孤街浪徒 提交于 2019-11-30 07:42:58

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');
  }
}

Flash movies are pretty much black boxes as far as javascript is concerned. If the SWF you're using wasn't written to interact with javascript then you're probably out of luck.

You'll either need to figure out what javascript methods the movie you're using exposes (hopefully it has documentation), find another one that does provide javascript interaction, or write your own SWF to handle it.

What you're looking for is the flash ExternalInterface class, which is used for communication from flash to javascript and from javascript to flash.

If you're embedding the player using swfobject you're going to want to use swfobject.getObjectById to get a reference to the movie. Read the docs to see why you need to do this.

Also you'll need to set {wmode:"transparent"} for the player in order for it to bubble up click events to JavaScript.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!