stamat / youtube-background

ESM / jQuery plugin for creating video backgrounds from YouTube, Vimeo or video file links.

Home Page:https://stamat.github.io/youtube-background/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How do you control the video once initialized?

d-packs opened this issue · comments

I'm using this in a slider and adding video to slides background.

I'd like to pause the video on the hidden slides and resume on the one currently in view.
I can handle the slider events, but I can't find the objects on which to call the pause() and play() methods.

//this is how I call the background init, it works great, the videos are initialized and start playing:
    $('.youtube-background[data-youtube]').youtube_background(); 

//and this is how I try to manipulate the video players
    $(window).bind("load",function(){
        $('.swiper-container' ).each(function(i){
            var swiperInstance = $(this).data( 'swiper' );
            swiperInstance.on('slideChange', function(){
//this returns a collection of slides:
                var video_slides = $(this.slides).find('.youtube-background');
// i've tried $('[data-youtube]'), but there is no such thing, apparently the script removes the data attribute of the element once youtube_background() has been called on it
                video_slides.each(function(i){
                    if (typeof $(this).pause === "function") {
                        $(this).pause(); //this is never reached
                    }
                });
                $(this.slides[this.activeIndex]).find('.youtube-background').each(function(i){
                    if (typeof $(this).play === "function") {
                        $(this).play(); //also never reached
                    }
                });
            });
        });
    });

Hey, thanks for posting this feature request.
I believe you can use Intersection Observer to detect the intersections and play or pause the videos as they scroll into the viewport.
If you take a look at the end of the latest code you'll see that there is VideoBackgrounds class initialised. If you add it to a global window variable of your choosing you will be then able to access the object's property index, and have a list of all YoutubeBackground objects initialised which you can use to toggle playing state.

Initialising the plugin vanilla way new VideoBackgrounds('[data-youtube]'); will let you access the VideoBackgrounds object without editing the source code.

Yes I plan to revisit this when I have more time on my hands. And I can make what you seek an automatic feature.

Thank you for your reply. And thank you for the work you've put into this. It works great.