Skip to content

Instantly share code, notes, and snippets.

@arifd
Created April 2, 2020 18:41
Show Gist options
  • Save arifd/03998860c86ccc106ddecb689aad4093 to your computer and use it in GitHub Desktop.
Save arifd/03998860c86ccc106ddecb689aad4093 to your computer and use it in GitHub Desktop.
Manually determine how much of a HTML element intersects with the viewport
// A function to know how much of a HTML element has been scrolled onto your viewport.
// Note: This should no longer be used, prefer: IntersectionObserver.
// https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver
const clamp = (val, min, max) => Math.min(Math.max(min, val), max);
getPercentVisible(element) {
const rect = element.getBoundingClientRect();
// If not even partially visible, return early
if (rect.top >= window.innerHeight || rect.bottom <= 0) return 0;
const topIsVisible = rect.top >= 0 && rect.top < window.innerHeight;
const bottomIsVisible = rect.bottom < window.innerHeight && rect.bottom >= 0;
const topCheck = function() {
const pixelsVisible = window.innerHeight - rect.top;
// const negativeSpace = window.innerHeight - negativeSpace;
const percentVisible = pixelsVisible / rect.height;
return percentVisible;
}
const bottomCheck = function() {
const negativeSpace = window.innerHeight - rect.bottom;
const pixelsVisible = clamp(window.innerHeight - negativeSpace, 0, rect.height);
const percentVisible = pixelsVisible / rect.height;
return percentVisible;
}
if (topIsVisible && bottomIsVisible) return 1;
else if (topIsVisible) return topCheck();
else if (bottomIsVisible) return bottomCheck();
else return -1; // something went wrong!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment