Skip to content

Instantly share code, notes, and snippets.

@nabrown
Last active November 30, 2018 17:47
Show Gist options
  • Save nabrown/e75f269abd65a015261501a5a262e81a to your computer and use it in GitHub Desktop.
Save nabrown/e75f269abd65a015261501a5a262e81a to your computer and use it in GitHub Desktop.
Unveil() function rewritten without jQuery
function unveil() {
// create an array of images that are in view
// by filtering the intial array
var inview = images.filter(function(img) {
// if the image is set to display: none
if (img.style.display === "none") return;
var rect = img.getBoundingClientRect(),
wt = window.scrollY, // window vertical scroll distance
wb = wt + w.innerHeight, // last point of document visible in browser window
et = wt + rect.top, // distance from document top to top of element
eb = wt + rect.bottom; // distance from top of document to bottom of element
// the bottom of the element is below the top of the browser (- threshold)
// && the top of the element is above the bottom of the browser (+ threshold)
return eb >= wt - th && et <= wb + th;
});
if (w.CustomEvent) {
var unveilEvent = new CustomEvent('unveil');
} else {
var unveilEvent = document.createEvent('CustomEvent');
unveilEvent.initCustomEvent('unveil', true, true);
}
inview.forEach(function(inviewImage){
inviewImage.dispatchEvent(unveilEvent);
});
// alternative -- two arrays: https://stackoverflow.com/questions/11731072/dividing-an-array-by-filter-function
// another possibility -- use getElementsByClassName which returns _live_ HTML Collection
// https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
images = [].slice.call(document.querySelectorAll("img.unveil"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment