0

I designed a website that has video. I want the video to start playing automatically every time Windows scrolls and reaches the video section. And when the user scrolls to a lower or higher section, video stop. And when you return to the video section, the video will play automatically.How to do this with JavaScript for a number of videos on one page.On the advice of a friend, I used "Intersection Observer API". This code works for one video, but does not work for multiple videos on one page.thanks.

const video = document.querySelectorAll("video");
for (let i = 0; i < video.length; i++) {
   const observer = new IntersectionObserver((entries) => {
       entries.forEach((entry) => {
          if (!entry.isIntersecting) {
              video.pause();
          } else {
              video.play();
          }
       });
   }, {});
  observer.observe(video);
}
<div>
  <div class="video-container">
     <video controls>
        <source src="http://itp.nyu.edu/~rnr217/HTML5/Week3/video/testopen.mp4" type="video/mp4">
         Your browser does not support the video tag.
     </video>
  </div>
</div>


<div>
  <div class="video-container">
     <video controls>
        <source src="http://itp.nyu.edu/~rnr217/HTML5/Week3/video/testopen.mp4" type="video/mp4">
         Your browser does not support the video tag.
     </video>
  </div>
</div>
  • Check if the video is playing first. – evolutionxbox Feb 17 '22 at 16:18
  • Also, does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – evolutionxbox Feb 17 '22 at 16:19

1 Answers1

1

Use the intersection API, so that once the video element comes into viewport you can play it and stop it once it leaves the viewport.

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API