FancyBox and Youtube API events

岁酱吖の 提交于 2019-11-28 14:33:45
Minime

Please see following working code (you should use version 2 of fancybox.)

jsfiddle: http://jsfiddle.net/c5h9U/2/

// Fires whenever a player has finished loading
function onPlayerReady(event) {
    event.target.playVideo();
}

// Fires when the player's state changes.
function onPlayerStateChange(event) {
    // Go to the next video after the current one is finished playing
    if (event.data === 0) {
        $.fancybox.close();
    }
}

// The API will call this function when the page has finished downloading the JavaScript for the player API
function onYouTubePlayerAPIReady() {

    // Initialise the fancyBox after the DOM is loaded
    $(document).ready(function() {
        $(".fancybox")
            .attr('rel', 'gallery')
            .fancybox({
                openEffect  : 'none',
                closeEffect : 'none',
                nextEffect  : 'none',
                prevEffect  : 'none',
                padding     : 0,
                margin      : 50,
                beforeShow  : function() {
                    // Find the iframe ID
                    var id = $.fancybox.inner.find('iframe').attr('id');

                    // Create video player object and add event listeners
                    var player = new YT.Player(id, {
                        events: {
                            'onReady': onPlayerReady,
                            'onStateChange': onPlayerStateChange
                        }
                    });
                }
            });
    // Launch fancyBox on first element
    $(".fancybox").eq(0).trigger('click');
    });

}

Possible causes:

  • Testing "locally" (loading the file without going through http://localhost)
  • Mixing Embed API (where you declare an iframe) with iframe API (where you declare a DIV and load some JS). The events only seem to work with the latter.
  • ID on the DIV does not match ID on new YT.Player(...) call
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!