YouTube API Target (multiple) existing iframe(s)

后端 未结 1 2208
傲寒
傲寒 2020-12-07 17:10

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 giv

1条回答
  •  不思量自难忘°
    2020-12-07 17:55

    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,

    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