Last active
April 20, 2022 05:56
-
-
Save akshar-dave/d8ba2bdad1bd36df0022aeecdf918256 to your computer and use it in GitHub Desktop.
Pause videos when not in view 🍿
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
}, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
😊