Skip to content

Instantly share code, notes, and snippets.

@hrahimi270
Forked from rijkvanzanten/percentage-in-view.js
Created January 20, 2022 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrahimi270/a4ef34485ff6d7386904b70252c5d33f to your computer and use it in GitHub Desktop.
Save hrahimi270/a4ef34485ff6d7386904b70252c5d33f to your computer and use it in GitHub Desktop.
Get how much percentage an element is in view in plain JavaScript
function getViewPercentage(element) {
const viewport = {
top: window.pageYOffset,
bottom: window.pageYOffset + window.innerHeight
};
const elementBoundingRect = element.getBoundingClientRect();
const elementPos = {
top: elementBoundingRect.y + window.pageYOffset,
bottom: elementBoundingRect.y + elementBoundingRect.height + window.pageYOffset
};
if (viewport.top > elementPos.bottom || viewport.bottom < elementPos.top) {
return 0;
}
// Element is fully within viewport
if (viewport.top < elementPos.top && viewport.bottom > elementPos.bottom) {
return 100;
}
// Element is bigger than the viewport
if (elementPos.top < viewport.top && elementPos.bottom > viewport.bottom) {
return 100;
}
const elementHeight = elementBoundingRect.height;
let elementHeightInView = elementHeight;
if (elementPos.top < viewport.top) {
elementHeightInView = elementHeight - (window.pageYOffset - elementPos.top);
}
if (elementPos.bottom > viewport.bottom) {
elementHeightInView = elementHeightInView - (elementPos.bottom - viewport.bottom);
}
const percentageInView = (elementHeightInView / window.innerHeight) * 100;
return Math.round(percentageInView);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment