Created
November 28, 2021 08:34
-
-
Save cstriuli/b161e2969b98efbaad932aad47873439 to your computer and use it in GitHub Desktop.
Autoplay videos
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 elements = document.querySelectorAll('video[data-autoplay]') | |
const observer = new IntersectionObserver(handleIntersection, { | |
rootMargin: '0px', | |
threshold: 0.7 | |
}) | |
let visibleVideos = new Set() | |
let previouslyVisibleVideos = null | |
function handleIntersection (entries, observer) { | |
entries.forEach((entry, index) => { | |
const video = entry.target | |
if (entry.isIntersecting) { | |
video.play() | |
visibleVideos.add(video) | |
} else { | |
visibleVideos.delete(video) | |
video.pause() | |
} | |
}) | |
} | |
function handleVisibilityChange (elements) { | |
if (document.hidden) { | |
if (!previouslyVisibleVideos) { | |
previouslyVisibleVideos = visibleVideos | |
visibleVideos = [] | |
previouslyVisibleVideos.forEach(video => video.pause()) | |
} | |
} else { | |
previouslyVisibleVideos.forEach(video => video.play()) | |
visibleVideos = previouslyVisibleVideos | |
previouslyVisibleVideos = null | |
} | |
} | |
export default { | |
bind: (rootEl) => { | |
elements.forEach((el, index) => { | |
observer.observe(el) | |
}) | |
document.addEventListener('visibilitychange', handleVisibilityChange, false) | |
}, | |
unbind: () => { | |
elements.forEach((el, index) => { | |
observer.unobserve(el) | |
}) | |
document.removeEventListener('visibilitychange', handleVisibilityChange, false) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment