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 ☕.
B2B Solution & Custom Pricing | Product Labels by BSS
Need help from our expert? Kindly share your request with us via community@bsscommerce.com
Hey Community! As the holiday season unfolds, we want to extend heartfelt thanks to a...
By JasonH Dec 6, 2024Dropshipping, a high-growth, $226 billion-dollar industry, remains a highly dynamic bus...
By JasonH Nov 27, 2024Hey Community! It’s time to share some appreciation and celebrate what we have accomplis...
By JasonH Nov 14, 2024