Videos paused outside viewport with IntersectionObserver

Viewed 574

I created this function that stops the videos from playing when they are outside the viewport. It doesn't work. Can you help fix it?

const observer = new IntersectionObserver(entries => { 
    entries.forEach(entry => {
        entry.intersectionRatio > 0 ? entry.target.play : entry.target.pause()
    })
})

const videos = document.querySelectorAll('video')   
videos.forEach(video => {
    console.log('video out')
    observer.observe(video)
})
1 Answers

Maybe you've found an answer already, but you're not actually invoking the .play method. You need to use .play() just like you used .pause(). So your third line should be:

entry.intersectionRatio > 0 ? entry.target.play() : entry.target.pause()
Related