Skip to content

Instantly share code, notes, and snippets.

@thesephist
Created November 24, 2016 05:27
Show Gist options
  • Save thesephist/14a876a17e31c6baba752c2a1c9848e8 to your computer and use it in GitHub Desktop.
Save thesephist/14a876a17e31c6baba752c2a1c9848e8 to your computer and use it in GitHub Desktop.
Detector for if an element is in-viewport
const THRESHOLD = 0.8; // I find this to be a good number
function isInViewPort(el) {
// getBoundingClientRect() compared with body scrolltop and innerHeight
const BCR = el.getBoundingClientRect();
const elTop = BCR.top;
const elWidth = BCR.height;
return (elTop > 0 && elTop < THRESHOLD * window.innerHeight) || elTop < 0;
}
function reveal(el) {
if (el.className.indexOf('appear') == -1) el.className += ' appear';
}
var revealingElements = Array.prototype.slice.apply(document.querySelectorAll(".reveal"));
function checkReveals() {
revealingElements.forEach(el => {
if (isInViewPort(el)) reveal(el);
});
}
$(window).scroll(checkReveals);
document.addEventListener('DOMContentLoaded', checkReveals);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment