- Change your
<video>
id to be a class, so that there can be multiple of them on a page. - Use
.querySelectorAll('video.local-video')
to get all video elements with the class name of.local-video
. - Loop through all of those elements, and play them accordingly.
Code:
<!-- Autoplay, on view video START-->
<script>
const localVideos = document.querySelectorAll('video.local-video'); // <= select ALL instances of .local-video
// Play the video when it's in the viewport
window.addEventListener('scroll', function() {
localVideos.forEach((video) => { // <= loop through ALL videos and perform your function
const rect = video.getBoundingClientRect();
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
if (rect.top >= 0 && rect.bottom <= windowHeight) {
video.play();
} else {
video.pause();
}
});
});
// Pause video when page is not visible
document.addEventListener('visibilitychange', function() {
localVideos.forEach((video) => { // <= also loop here
if (document.hidden) {
video.pause();
} else {
video.play();
}
});
});
</script>
<!-- Autoplay, on view video END-->
<div id="video-container">
<video class="local-video" loop controls>
<source src="<?php echo $video ?>" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>