user2499210
user2499210

Reputation: 11

Is it possible to start Fancybox on page load with a youtube video automatic and close at end automatic?

Is it possible to start Fancybox on page load with a Youtube video automatically and to close automatically at the end of the video? (A kind of intro)

Upvotes: 1

Views: 3521

Answers (1)

JFK
JFK

Reputation: 41143

Yes, it's possible. Take the example at the fancybox website (tips & tricks No.15), and tweak it to your needs.

First, you would need to load the youtube player API (apart from the jQuery and fancybox js and css files of course)

<script src="http://www.youtube.com/player_api"></script>

Then built the onYouTubePlayerAPIReady() function with the fancybox custom script inside of it to launch the video.

Then, inside the fancybox beforeShow callback, set a listener for the end of the video and close fancybox using the method $.fancybox.close() like :

function onYouTubePlayerAPIReady() {
    $(document).ready(function () {
        $.fancybox({
            href: "http://www.youtube.com/embed/L9szn1QQfas?enablejsapi=1&wmode=opaque&autoplay=1",
            type: "iframe",
            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: {
                        'onStateChange': function (event) {
                            if (event.data === 0) {
                                $.fancybox.close();
                            } // if
                        } // onStateChange
                    } // events
                }); // YT.Player
            } // beforeShow
        }); // fancybox
    }); // ready
} // onYouTubePlayerAPIReady

See JSFIDDLE

Upvotes: 2

Related Questions