HTML5-Background-Video
HTML5-Background-Video copied to clipboard
Autoplay/pause videos when in/out of viewport
Is it possible to have the video backgrounds autopause, when scrolled past them and to only play, when they are visible in the window? I two video background sections on one page, and the first video, which is all the way in the top as a banner, is working fine and stops at the right time when I scroll past it but the other video further down also plays/pauses according to the first video in the top.
I have used this script:
var videos = document.getElementsByTagName("video"),
fraction = 0.8;
function checkScroll() {
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
Thanks :)
Hi, did you find a solution for this? I have the same problem, 3 videos, and the first one control the others... here is what happens http://185.197.128.183/~monompro/
thanks!