Skip to content

Instantly share code, notes, and snippets.

@cstriuli
Created November 28, 2021 08:34
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 cstriuli/b161e2969b98efbaad932aad47873439 to your computer and use it in GitHub Desktop.
Save cstriuli/b161e2969b98efbaad932aad47873439 to your computer and use it in GitHub Desktop.
Autoplay videos
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