Diptendu
Diptendu

Reputation: 2158

How to tell what fraction of element is inside viewport?

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

Answers (1)

momotaro
momotaro

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

Related Questions