-
-
Save hrahimi270/a4ef34485ff6d7386904b70252c5d33f to your computer and use it in GitHub Desktop.
Get how much percentage an element is in view in plain JavaScript
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
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