I'm trying to understand how to target an existing iframe using the YouTube API (i.e. without constructing an iframe with the script).
As usual, Google does not give enough API examples, but explains that it IS possible, here http://code.google.com/apis/youtube/iframe_api_reference.html
Here is an example of what I'm trying to do - the video underneath the thumbnail should play. I am almost there, but only the first video plays...
TL;DR: DEMO: http://jsfiddle.net/KtbYR/5/
YT_ready
,getFrameID
andonYouTubePlayerAPIReady
are functions as defined in this answer. Both methods can be implemented without any preloaded library. In my previous answer, I showed a method to implement the feature for a single frame.In this answer, I focus on multiple frames.
HTML example code (important tags and attributes are capitalized,
<iframe src id>
):JavaScript code (
YT_ready
,getFrameID
,onYouTubePlayerAPIReady
and the YouTube Frame API script loader are defined here)In my previous answer, I bound the
onStateChange
event. In this example, I used theonReady
event, because you want to call the functions only once, at initialization.This example works as follows:
The following methods are defined in this answer.
onYoutubePlayerAPIReady
is called, which in his turn activates all functions as defined usingYT_ready
The declaration of the following methods are shown here, but implemented using this answer. Explanation based on the example:
<iframe id>
object, which is placed right after<.. class="thumb">
.id
is retrieved, and stored in theidentifier
variable.getFrameID
. This ensures that the<iframe>
is properly formatted for the API. In this example code, the returned ID is equal toidentifier
, because I have already attached an ID to the<iframe>
.<iframe>
exists, and a valid YouTube video, a new player instance is created, and the reference is stored in theplayers
object, accessible by keyframeID
.onReady
* event is defined. This method will be invoked when the API is fully initialized for the frame.createYTEvent
This method returns a dynamically created function, which adds functionality for separate players. The most relevant parts of the code are:
frameID
is the ID of the frame, used to enable the YouTube Frame API.identifier
is the ID as defined inYT_ready
, not necessarily an<iframe>
element.getFrameID
will attempt to find the closest matching frame for a given id. That is, it returns the ID of a given<iframe>
element, or: If the given element is not an<iframe>
, the function looks for a child which is a<iframe>
, and returns the ID of this frame. If the frame does not exists, the function will postfix the given ID by-frame
.Make sure that you also check this answer, because the core functionality of this answer is based on that.
Other YouTube Frame API answers. In these answers, I showed various implementations of the YouTube Frame/JavaScript API.