Created
November 24, 2016 05:27
-
-
Save thesephist/14a876a17e31c6baba752c2a1c9848e8 to your computer and use it in GitHub Desktop.
Detector for if an element is in-viewport
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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