Skip to content

Instantly share code, notes, and snippets.

@ll931217
Created November 11, 2024 01:46
Show Gist options
  • Save ll931217/cef87a5a489d40eb293c8282e3114637 to your computer and use it in GitHub Desktop.
Save ll931217/cef87a5a489d40eb293c8282e3114637 to your computer and use it in GitHub Desktop.
Autoplay Video on scroll by checking if video is in viewport
<video id="myVideo" src="video.mp4" muted></video>
<script>
const video = document.getElementId("myVideo");
function autoplayVideo() {
const rect = video.getBoundingClientRect();
if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
video.play();
} else {
video.pause();
}
}
window.addElementListener("scroll", autoplayVideo);
window.addElementListener("resize", autoplayVideo);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment