Last active
January 18, 2022 14:52
-
-
Save johnfmorton/88871701abc4f2d4eac2d4e3140c6c47 to your computer and use it in GitHub Desktop.
Play an ambient video (muted inlin
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
var ambientVideo = document.getElementById("ambientVideo"); | |
/** | |
// in HTML page | |
<video muted playsinline id='abientVideo'> | |
<source src="my-video-file.webm" type="video/webm"> | |
</video> | |
**/ | |
var io = new IntersectionObserver( | |
entries => { | |
entries.forEach(entry => { | |
if (entry.isIntersecting) { | |
ambientVideo.play(); | |
} else { | |
ambientVideo.pause(); | |
} | |
}); | |
}, | |
{ | |
// options: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#intersection_observer_options | |
root: null, | |
rootMargin: "0px", | |
threshold: 0.5 | |
} | |
); | |
// after confirming the element exists, look for the #ambientVideo when visible in viewport | |
if (ambientVideo) { | |
io.observe(ambientVideo) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment