Search code examples
javascriptjqueryyoutube-api

Enable YouTube API on existing player


I have an embeded youtube video which I want the YouTube API applied. I add the url parameter using jQuery as follows (demo):

$(document).ready(function(){
 var obj = $('object');
 obj.find('embed').attr('src', function(i,s){return s+'&enablejsapi=1&version=3'})
 obj.find('param[name=movie]').attr('value', function(i,v){return v+'&enablejsapi=1&version=3'})

 $('.play').click(function(){
  obj.find('embed')[0].playVideo();
 });
 $('.pause').click(function(){
  obj.find('embed')[0].pauseVideo();
 })
});

This method works great in Firefox, but not at all in IE or Chrome (not sure about other browsers). So my question is how do I modify this to make the API work in other browsers? Would I have to completely remove the object and replace it using SWFObject?

Note: The embed code is directly from YouTube.


Update: I figured out if I remove the object, add the url parameters then add the object back, I can now get it to work in Chrome, but still not IE (updated demo).


Addendum: Why doesn't the YouTube API function when the object/embed already has the enable code within it? I'm trying to avoid making SWFObject a dependancy.

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="640" height="385">
 <param name="movie" value="http://www.youtube.com/v/2Qj8PhxSnhg&amp;hl=en_US&amp;fs=1&enablejsapi=1&version=3"></param>
 <param name="allowFullScreen" value="true"></param>
 <param name="allowscriptaccess" value="always"></param>
 <embed src="http://www.youtube.com/v/2Qj8PhxSnhg&amp;hl=en_US&amp;fs=1&enablejsapi=1&version=3" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>
</object>

Solution

  • Regarding swfobject - yes. IE treats flash embeds slightly differently (thanks activex) than all the other browsers. check out this article to get an idea of why, and the SWFObject documentation for more information.

    Also, I recently created a jQuery plugin to help control the embedded player using the player API (basically what you're doing).

    Check it out, it's the jQuery TubePlayer plugin - http://www.tikku.com/jquery-youtube-tubeplayer-plugin