Skip to content

Instantly share code, notes, and snippets.

@colorincode
Created October 1, 2024 18:42
Show Gist options
  • Save colorincode/9f0b9c97108488484eeb31ced92a02d8 to your computer and use it in GitHub Desktop.
Save colorincode/9f0b9c97108488484eeb31ced92a02d8 to your computer and use it in GitHub Desktop.
// this is an intersection observer in cases where you have video that is outta focus
function setupVideoObservers() {
const videos = document.querySelectorAll('.some-video');
let currentVideo: HTMLVideoElement | null = null;
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const video = entry.target as HTMLVideoElement;
if (entry.isIntersecting) {
video.play();
//you dont have to modify attributes, but I often do depending on context
video.controls = true;
video.autoplay = true;
video.loop = true;
currentVideo = video;
} else {
video.pause();
video.controls = false;
video.autoplay = false;
video.loop = false;
// webkit prefers this, for some reason.
if (currentVideo === video) {
currentVideo = null;
}
}
});
}, { threshold: 0.5 });
videos.forEach(video => observer.observe(video));
// u really only need this part
document.addEventListener('keydown', (event) => {
if (event.code === 'Space' && currentVideo) {
event.preventDefault(); // prevent scrolling, u may or may not want this
if (currentVideo.paused) {
currentVideo.play();
} else {
currentVideo.pause();
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment