Search code examples
javascriptjquerycssvideoviewport

Pause and play video when in viewport


I was experimenting with play and pause when a video is within the viewport... when I was searching around I found the following code.. which unfortunately didn't work:

jQuery

    $(window).scroll(function(){
        if ($(window).scroll(100)){
            $('#video').play;
        }
    });

HTML

    <video preload="auto" loop="loop" id="background">
        <source src="background/background1.mp4" type="video/mp4"> </source>
        <source src="background/background1.webm" type="video/webm"> </source>
    </video>

I've also tried the code on the following page: http://serversideguy.com/2014/02/05/play-youtube-videos-on-scroll-over/

but I couldn't get it to work either, is there anyone who could point me in the right direction?

Is it even practical to play and pause video's when in / out of the viewport, wouldn't users be startled by sounds suddenly appearing?


Solution

  • I agree with what you said in your question: users might not like it, especially if they're on mobile and you're sucking all their data plan. Anyway, here's how to check if an element is in the viewport: http://jsfiddle.net/pwhjk232/

    $(document).ready(function() {
        var inner = $(".inner");
        var elementPosTop = inner.position().top;
        var viewportHeight = $(window).height();
        $(window).on('scroll', function() {
            var scrollPos = $(window).scrollTop();
            var elementFromTop = elementPosTop - scrollPos;
    
            if (elementFromTop > 0 && elementFromTop < elementPosTop + viewportHeight) {
                inner.addClass("active");
            } else {
                inner.removeClass("active");
            }
        });
    })
    

    Instead of using addClass you could use .get(0).play() and .get(0).pause() as suggested by Vohuman