Skip to content

Instantly share code, notes, and snippets.

@rijkvanzanten
Last active December 8, 2023 18:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rijkvanzanten/df73ae28e80b9c6e5030baed4d1a90a6 to your computer and use it in GitHub Desktop.
Save rijkvanzanten/df73ae28e80b9c6e5030baed4d1a90a6 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);
}
@uolpatrickward
Copy link

uolpatrickward commented Sep 16, 2020

Hi,
Testing this in a codepen for multiple items. Seems to work for all but the first and last items. Any idea why?
https://codepen.io/standardspace/pen/oNxMQPV?

@rijkvanzanten
Copy link
Author

rijkvanzanten commented Sep 16, 2020

@uolpatrickward Your codepen works for me! 🤷

https://cln.sh/YngpnD

@uolpatrickward
Copy link

But your video shows that the first and last don't reach 100%. This seems to be down to the spacing I've edited the codepen and it works now. Thanks for taking a look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment