Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?
There is a new API for this scenario, called Intersection_Observer_API, which Chrome 51+ and Edge 15+ has supported.
var options = {
root: document.querySelector('.scroll-container'),
rootMargin: '0px',
threshold: 1.0 // trigger only when element comes into view completely
};
var ob = new IntersectionObserver((entries, observer) => {
entries[0].target.classList.toggle('red');
}, options);
// observe all targets, when coming into view, change color
document.querySelectorAll('.target').forEach((item) => {
ob.observe(item);
});
Here is a simple demo: https://codepen.io/hectorguo/pen/ybOKEJ