0

So I've gone through multiple questions on here and can't seem to work out a way to achieve my goal.

I have a page with multiple 'video' tags. Now I want them to play once they are visible.

I've referenced this question: HTML5 and Javascript to play videos only when visible as a main basis.

I'm currently using this code:

$(window).on('scroll', function() {
  $('video').each(function() {
      if ($(this).visible(true)) {
          $(this)[0].play();
        }
  })
});

Which works though the videos replay every time I scroll even in the slightest. If I add an unbind to the function, then only the first video works. Also, if I do something along the lines of this:

var played = false;

$(window).on('scroll', function() {
  $('video').each(function() {
      if ($(this).visible(true) && played == false) {
          $(this)[0].play();
        }
        played = true;
  })
});

The second, third etc videos do not play either.

I'm wondering if there's a way to grab all video tags and play them only once and only when they become visible on the screen.

joshzee
  • 187
  • 1
  • 12
  • The referenced question mentions `IntersectionObserver` - that is probably the best approach – Professor Abronsius Jul 01 '21 at 07:01
  • Have you tried using a data attribute, setting the data attribute to a boolean value once played => `true`? Then check the data attributes value if not `true` play video... – dale landry Jul 01 '21 at 07:01

0 Answers0