0

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?

Community
  • 1
  • 1
Diptendu
  • 2,120
  • 1
  • 15
  • 28
  • Can you be more specific mate? What are we talking about here? The percentage of a whole element's area? – Leo Dec 16 '14 at 09:19
  • Yes, (Area of an element inside viewport) / Total area taken by the element. For example there is a
    whose height is 10px and width is 10px. So, total area is 100 sq unit. Now, the area of the
    inside viewport is (height * width) inside viewport.
    – Diptendu Dec 16 '14 at 09:22

1 Answers1

1

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.

momotaro
  • 135
  • 1
  • 5