Reputation: 2158
How to determine what percentage of a DOM element is inside the current viewport ? I want to calculate the ratio of area of element inside viewport and the total area of the element.
Related question: How to tell if a DOM element is visible in the current viewport?
Upvotes: 0
Views: 319
Reputation: 145
See getBoundingClientRect
and Window.innerHeight
.
let {top, height} = element.getBoundingClientRect(),
percentVisible = Math.max(0, Math.min(1, (window.innerHeight - top) / height));
I'm guessing at your use case, but in modern browsers, see IntersectionObserver
and its intersectionRatio
.
Upvotes: 1