Sometimes, we want to play videos only when visible with HTML5 and JavaScript.
In this article, we’ll look at how to play videos only when visible with HTML5 and JavaScript.
How to play videos only when visible with HTML5 and JavaScript?
To play videos only when visible with HTML5 and JavaScript, we can use the Intersection Observer to check if the video is completely in the screen.
For instance, we write:
<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4' autoplay="autoplay" controls style='height: 200px'></video>
to add a video element with autoplay enabled.
Then we write:
const video = document.querySelector('video');
let isPaused = false;
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.intersectionRatio !== 1 && !video.paused) {
video.pause();
isPaused = true;
} else if (isPaused) {
video.play();
isPaused = false
}
});
}, {
threshold: 1
});
observer.observe(video);
to get the video with document.querySelector
.
Then we create a new IntersectionObserver
instance with a callback that checks if the video is fully in the screen and isn’t paused with entry.intersectionRatio !== 1 && !video.paused
.
If both are true, then we pause the video.
Otherwise, we play the video.
Then we call observer.observer
to watch when the video is in the screen.
Conclusion
To play videos only when visible with HTML5 and JavaScript, we can use the Intersection Observer to check if the video is completely in the screen.