Search code examples
jqueryvideoviewportautoplaypause

If video has prop autoplay don't pause when out of viewport


I am using isinViewport from https://github.com/zeusdeux/isInViewport to play/pause videos when in/out of view. But sometimes I don't want them to autoplay (for videos that are not muted and with controls).

Hence I am checking for if is in viewport & with property autoplay

jQuery(document).ready(function ($) {
    "use strict";
    
    /* activate pause for lightbulb video if scrolled out of viewport */
    $(window).scroll(function() {
        $('video').each(function(){
            if ($(this).is(":in-viewport()") && $(this).prop('autoplay')) {
                $(this)[0].play();
            } else {
                $(this)[0].pause();
            }
        });
    });
});

Now. This works great. But, my videos that are set to autoplay stop once you scroll a bit and this is not desirable behaviour. Is there a way to sort of say: else, and with prop autoplay, do nothing?

Perhaps I need two different if statements. If with prop autoplay do nothing? else if play, and else pause?

All help in the right direction appreciated


Solution

  • You can include an attribute selector in the video selector to exclude the videos which have autoplay set on them when the page loads from the scroll update logic.

    jQuery($ => {
      "use strict";
      let $videos = $('video:not([autoplay])');
    
      /* activate pause for lightbulb video if scrolled out of viewport */
      $(window).on('scroll', () => {
        $videos.each(function() {
          $(this).is(":in-viewport()") ? this.play() : this.pause();
        });
      });
    });
    

    Note that I amended the logic slightly so that you avoid creating jQuery objects within the scroll event handler, which can be a massive performance drain, and also redundant in cases where $(this)[0] can be replaced with just this.