HTML5 and Javascript to play videos only when visible
Using the isInViewport plugin and jQuery, here's my code for the task
$('video').each(function(){
if ($(this).is(":in-viewport")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
})
OK, I think, it must be something like this:
var videos = document.getElementsByTagName("video");
function checkScroll() {
var fraction = 0.8; // Play when 80% of the player is visible.
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);
None of the above seemed to work for me, but I finally found a way: you'll need the visible
plugin, and this little piece of code right here:
$(window).scroll(function() {
$('video').each(function() {
if ($(this).visible(true)) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
})
});
This will allow any video to play only when it gets into viewport. By replacing visible( true )
by visible()
, you can set it to play only when the entire video DOM element is in viewport.