Last active
August 15, 2024 22:08
-
-
Save jairusjoer/12bb0c7c6b9a9a4293b01b1bd2013062 to your computer and use it in GitHub Desktop.
Sync video playback with vertical scrolling
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
const scrollVideo = (media, threshold = 1) => { | |
const video = document.querySelector(media); | |
const target = video.parentNode; | |
const scrollDistance = target.clientHeight - window.innerHeight; | |
let observer = new IntersectionObserver( | |
(entries, observer) => { | |
entries.forEach((entry) => { | |
if (entry.isIntersecting) { | |
window.onscroll = () => { | |
const scrollBase = window.scrollY - target.offsetTop; | |
const calcY = (video.duration / scrollDistance) * scrollBase; | |
video.currentTime = calcY.toFixed(3); | |
}; | |
} | |
}); | |
}, | |
{ threshold: threshold / (target.clientHeight / window.innerHeight) } | |
); | |
observer.observe(target); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment