@Under S. wrote:
Greetings DW community!
What's the simplest 2023 method of autoplaying/autopausing a locally hosted video based on when it scrolls in or out of view?
Can this be done without javascript?
Modern way is using the javascript 'intersection observer' api.
For instance say you have a video with the class of myVideo:
<video muted loop class="myVideo">
<source src="video.mp4" type="video/mp4">
</video>
You could then use the 'intersection observer' to observer when the video comes in and out of the browsers viewport by adding the block of javascript code below to your pages code directly before the closing </body> tag.
<script>
function playVideo(video) {
video.forEach(function(video) {
//if the video is visible play the video, else pause the video
if (video.isIntersecting) {
video.target.play();
}
else {
video.target.pause();
}
})
}
// Create the observer
let observer = new IntersectionObserver(playVideo, {
threshold: 0.3
});
// Get and observe all the items with the class of myVideo
let video = document.querySelectorAll('.myVideo');
video.forEach(function(video) {
observer.observe(video);
});
</script>