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>