YouTube API Target (multiple) existing iframe(s)

故事扮演 提交于 2019-11-27 17:54:15
Rob W

TL;DR: DEMO: http://jsfiddle.net/KtbYR/5/

YT_ready, getFrameID and onYouTubePlayerAPIReady 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>):

<div>
  <img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
  <IFRAME ID="frame1" SRC="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" width="640" height="390" frameborder="0"></IFRAME>
</div>
<div>
  <img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
  <IFRAME ID="frame2" SRC="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" width="640" height="390" frameborder="0"></IFRAME>
</div>

JavaScript code (YT_ready, getFrameID, onYouTubePlayerAPIReady and the YouTube Frame API script loader are defined here)

var players = {}; //Define a player storage object, to expose methods,
                  //  without having to create a new class instance again.
YT_ready(function() {
    $(".thumb + iframe[id]").each(function() {
        var identifier = this.id;
        var frameID = getFrameID(identifier);
        if (frameID) { //If the frame exists
            players[frameID] = new YT.Player(frameID, {
                events: {
                    "onReady": createYTEvent(frameID, identifier)
                }
            });
        }
    });
});

// Returns a function to enable multiple events
function createYTEvent(frameID, identifier) {
    return function (event) {
        var player = players[frameID]; // Set player reference
        var the_div = $('#'+identifier).parent();
        the_div.children('.thumb').click(function() {
            var $this = $(this);
            $this.fadeOut().next().addClass('play');
            if ($this.next().hasClass('play')) {
                player.playVideo();
            }
        });
    }
}

In my previous answer, I bound the onStateChange event. In this example, I used the onReady 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.

    1. The YouTube Frame API is loaded from http://youtube.com/player_api.
    2. When this external script has finished loading, onYoutubePlayerAPIReady is called, which in his turn activates all functions as defined using YT_ready
  • The declaration of the following methods are shown here, but implemented using this answer. Explanation based on the example:

    1. Loops through each <iframe id> object, which is placed right after <.. class="thumb">.
    2. At each frame element, the id is retrieved, and stored in the identifier variable.
    3. The internal ID of the iframe is retrieved through getFrameID. This ensures that the <iframe> is properly formatted for the API. In this example code, the returned ID is equal to identifier, because I have already attached an ID to the <iframe>.
    4. When the <iframe> exists, and a valid YouTube video, a new player instance is created, and the reference is stored in the players object, accessible by key frameID.
    5. At the creation of the player instance, a **onReady* event is defined. This method will be invoked when the API is fully initialized for the frame.
    6. createYTEvent
      This method returns a dynamically created function, which adds functionality for separate players. The most relevant parts of the code are:

      function createYTEvent(frameID, identifier) {
          return function (event) {
              var player = players[frameID]; // Set player reference
              ...
                      player.playVideo();
          }
      }
      
      • frameID is the ID of the frame, used to enable the YouTube Frame API.
      • identifier is the ID as defined in YT_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.
      • players[playerID]` refers to the initialized player instance.

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.

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