Created
April 2, 2020 18:41
-
-
Save arifd/03998860c86ccc106ddecb689aad4093 to your computer and use it in GitHub Desktop.
Manually determine how much of a HTML element intersects with the viewport
This file contains 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
// 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