Skip to content

Instantly share code, notes, and snippets.

@jairusjoer
Last active December 9, 2022 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jairusjoer/12bb0c7c6b9a9a4293b01b1bd2013062 to your computer and use it in GitHub Desktop.
Save jairusjoer/12bb0c7c6b9a9a4293b01b1bd2013062 to your computer and use it in GitHub Desktop.
Sync video playback with vertical scrolling
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