Created
November 11, 2024 01:46
-
-
Save ll931217/cef87a5a489d40eb293c8282e3114637 to your computer and use it in GitHub Desktop.
Autoplay Video on scroll by checking if video is in viewport
This file contains hidden or 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
<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