In this article, we're going to discuss how to use IntersectionObserver to make video clips play only when in the viewport (then stop as the visitor continues to scroll).
This is a perfect solution for long video clips that you want to make sure the visitor watches (get the benifits of autoplay, but ensure that the video is only playing when in viewport so the visitor doesn't miss out on anything important).
How will we do this with pure Javascript? Easy... IntersectionObserver.
This API can be used in many ways, but we're going to focus on the video-specific implementation.
A common use case would be an advertisement with autoplay enabled (plays as soon as it loads), and then stops when out of viewport. This ensures all visitors see the ad.
const video = document.querySelector("video");
let playState = null;
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
video.pause();
playState = false;
} else {
video.play();
playState = true;
}
});
}, {});
observer.observe(video);
const onVisibilityChange = () => {
if (document.hidden || !playState) {
video.pause();
} else {
video.play();
}
};
document.addEventListener("visibilitychange", onVisibilityChange);
Code language: JavaScript (javascript)
What do you need to do? Nothing but change the following line, to be more specific:
querySelector("video");
Code language: JavaScript (javascript)