2

I'm pretty new to jquery, so I snagged this code from another stackoverflow question, but I don't know how to adapt it.

I have a video that autoplays when it scrolls into the window. However, if the video is paused and the user scrolls even one pixel, the video starts again. I would like the video to stay paused if it is still in the window while the user is scrolling.

Ideally, if the video went completely out of view and then back in, the autoplay would run again. It would also work if this autoplay feature ran only once and and the user could choose to play the video again if they wanted.

$(document).ready(function() {
    // Get media - with autoplay disabled (audio or video)
    var media = $('.autoplay').not("[autoplay='autoplay']");
    var tolerancePixel = 40;

    function checkMedia() {
        // Get current browser top and bottom
        var scrollTop = $(window).scrollTop() + tolerancePixel;
        var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel;

        media.each(function(index, el) {
            var yTopMedia = $(this).offset().top;
            var yBottomMedia = $(this).height() + yTopMedia;

            if (scrollTop < yBottomMedia && scrollBottom > yTopMedia)
                $(this).get(0).play();
            else
                $(this).get(0).pause();
        });
    }

    $(document).on('scroll', checkMedia);
});
Eloims
  • 5,106
  • 4
  • 25
  • 41

1 Answers1

0

just mark the element as played

 if( scrollTop < yBottomMedia && scrollBottom > yTopMedia){
              if (!$(el).attr('data-played')){
                $(el).attr('data-played',1);
                $(this).get(0).play();
               }
            } else {
                $(this).get(0).pause();
            }
adrianj98
  • 584
  • 2
  • 9