J'ai commencé par lire toutes les vidéos visibles, mais les vieux téléphones ne fonctionnaient pas bien. Donc, actuellement, je lis la vidéo la plus proche du centre de la fenêtre et je mets les autres en pause. Vanilla JS. Vous pouvez choisir l'algorithme que vous préférez.
//slowLooper(playAllVisibleVideos);
slowLooper(playVideoClosestToCenter);
function isVideoPlaying(elem) {
if (elem.paused || elem.ended || elem.readyState < 2) {
return false;
} else {
return true;
}
}
function isScrolledIntoView(el) {
var elementTop = el.getBoundingClientRect().top;
var elementBottom = el.getBoundingClientRect().bottom;
var isVisible = elementTop < window.innerHeight && elementBottom >= 0;
return isVisible;
}
function playVideoClosestToCenter() {
var vids = document.querySelectorAll('video');
var smallestDistance = null;
var smallestDistanceI = null;
for (var i = 0; i < vids.length; i++) {
var el = vids[i];
var elementTop = el.getBoundingClientRect().top;
var elementBottom = el.getBoundingClientRect().bottom;
var elementCenter = (elementBottom + elementTop) / 2.0;
var windowCenter = window.innerHeight / 2.0;
var distance = Math.abs(windowCenter - elementCenter);
if (smallestDistance === null || distance < smallestDistance) {
smallestDistance = distance;
smallestDistanceI = i;
}
}
if (smallestDistanceI !== null) {
vids[smallestDistanceI].play();
for (var i = 0; i < vids.length; i++) {
if (i !== smallestDistanceI) {
vids[i].pause();
}
}
}
}
function playAllVisibleVideos(timestamp) {
// This fixes autoplay for safari
var vids = document.querySelectorAll('video');
for (var i = 0; i < vids.length; i++) {
if (isVideoPlaying(vids[i]) && !isScrolledIntoView(vids[i])) {
vids[i].pause();
}
if (!isVideoPlaying(vids[i]) && isScrolledIntoView(vids[i])) {
vids[i].play();
}
}
}
function slowLooper(cb) {
// Throttling requestAnimationFrame to a few fps so we don't waste cpu on this
// We could have listened to scroll+resize+load events which move elements
// but that would have been more complicated.
function repeats() {
cb();
setTimeout(function() {
window.requestAnimationFrame(repeats);
}, 200);
}
repeats();
}