How to stop a video from playing when I scroll away from the video

Hello!

I have set up videos on our home page and I’d like them to stop playing when they’re not in view. Right now they continue to play even after scrolling past the video.

Is there any way to do this?

My theme is craft theme and the link to the website is saaah.org.

Thank you in advance for any assistance!

Consider using the Intersection Observer API:

document.addEventListener('DOMContentLoaded', (event) => {
    let section = document.getElementById('shopify-section-template--22155907236124__custom_liquid_xJMmQY')
    let video = section.querySelector('video')

    let options = {
        root: null, // using the viewport as the bounding box
        rootMargin: '0px',
        threshold: 0.5 // trigger when 50% of the video is visible
    }

    let observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.isIntersecting) {
                video.play()
            } else {
                video.pause()
            }
        })
    }, options)

    observer.observe(video)
})

Hi @supporths ,

To do that follow these instructions:

  • Access your Shopify admin page, select Themes
  • Select Edit code
![view - 2024-04-01T144313.239.png|1756x778](upload://b9vuJkMaa2hXuBUCqIIz7XX7k3t.png)

In the code folder, find the theme.liquid file.
Add the following code after the paragraph:

<script>
var video = document.querySelector('deferred-media video');

function isElementInViewport(el) {
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

function handleVideoPlayback() {
    if (isElementInViewport(video)) {
        video.play();
    } else {
        video.pause();
    }
}

window.addEventListener('scroll', handleVideoPlayback);
window.addEventListener('resize', handleVideoPlayback);

handleVideoPlayback();
</script>

Hope it helps @supporths