All things Shopify and commerce
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
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 ☕.
Product Labels by BSS | B2B Solution & Custom Pricing
Need help from our expert? Kindly share your request with us via community@bsscommerce.com
Learn how to build powerful custom workflows in Shopify Flow with expert guidance from ...
By Jacqui May 7, 2025Did You Know? May is named after Maia, the Roman goddess of growth and flourishing! ...
By JasonH May 2, 2025Discover opportunities to improve SEO with new guidance available from Shopify’s growth...
By Jacqui May 1, 2025