Skip to content

detect what percentage of an HTML element is inside the window

Notifications You must be signed in to change notification settings

JenGL/div_in_viewport

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

Detect what percentage of the element is visible in window

function percVisible(el) {
  const rect = el.getBoundingClientRect();
  const windowHeight = (window.innerHeight || document.documentElement.clientHeight);
  const windowWidth = (window.innerWidth || document.documentElement.clientWidth);

  const left = Math.max(rect.left, 0);
  const right = Math.min(rect.right, windowWidth);
  const bottom = Math.min(rect.bottom, windowHeight);
  const top = Math.max(rect.top, 0);

  if (left < right && bottom > top) {
    return (right - left) * (bottom - top) / ((rect.right - rect.left) * (rect.bottom - rect.top));
  }
  return 0;
}

Working Example

https://jsfiddle.net/z0x5j6nd/1/

About

detect what percentage of an HTML element is inside the window

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published