Skip to content

Instantly share code, notes, and snippets.

@genesisneo
Last active February 24, 2021 11:06
Show Gist options
  • Save genesisneo/3b1ac86cc4c8a9256d5c5f8da97a230f to your computer and use it in GitHub Desktop.
Save genesisneo/3b1ac86cc4c8a9256d5c5f8da97a230f to your computer and use it in GitHub Desktop.
Small javascript for playing/pausing the video when in/out of the viewport
var videos = document.getElementsByTagName("video");
function checkViewport () {
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,
b = y + h,
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 > 0.5) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkViewport, false);
window.addEventListener('resize', checkViewport, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment