Skip to content

Instantly share code, notes, and snippets.

@akshar-dave
Last active April 20, 2022 05:56
Show Gist options
  • Save akshar-dave/d8ba2bdad1bd36df0022aeecdf918256 to your computer and use it in GitHub Desktop.
Save akshar-dave/d8ba2bdad1bd36df0022aeecdf918256 to your computer and use it in GitHub Desktop.
Pause videos when not in view 🍿

Pause videos when not in view

// pause video playback when not in view
useEffect(() => {
let observerOptions = {
rootMargin: "0px",
threshold: [0.25, 0.75] // start playing when 25% and 75% of the element is in view
};
// watch all selected videos and control playback when they enter the viewport
let handlePlay = (entries, videoObserver) => {
entries.forEach((entry) => {
let videoElement = entry.target;
if (entry.isIntersecting) {
videoElement.play();
} else {
videoElement.pause();
}
});
};
let videoObserver = new IntersectionObserver(handlePlay, observerOptions);
// select all the videos on page and observe them
let videos = document.querySelectorAll("video");
videos.forEach((video) => {
videoObserver.observe(video);
});
// cleanup
return () => {
videoObserver.disconnect();
}
}, []);
@akshar-dave
Copy link
Author

😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment