What's your biggest current challenge? Have your say in Community Polls along the right column.

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

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

supporths
Excursionist
18 0 4

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!

Replies 2 (2)

BEAUBUS
Shopify Partner
5 0 1

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)
})

 

Add browser tab, bookmarks and search favicon to your store with BEAUBUS Favicons (Free). Craft lightweight, sharp, and SEO-friendly vector banners with BEAUBUS Banners (Free plan available).

BSS-Commerce
Shopify Partner
3477 463 547

Hi @supporths ,

To do that follow these instructions:
- Access your Shopify admin page, select Themes
- Select Edit code

view - 2024-04-01T144313.239.png

In the code folder, find the theme.liquid file.
Add the following code after the </body> 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  

If our suggestions are useful, please let us know by giving it a like, marking it as a solution, or donating here .


B2B Solution & Custom Pricing | Product Labels by BSS


Need help from our expert? Kindly share your request with us via community@bsscommerce.com


BSS Commerce - Full-service eCommerce Agency