Wie man überprüft ob ein Element im Viewport ist (JS/TypeScript)

Scrolled Distance: JS %
/**
 * check if element is partially or fully in viewport
 * @param {Element} el
 * @returns {boolean}
 */
function isInViewport(el: Element) {
  const rect = el.getBoundingClientRect();

  return (
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) 
    && rect.bottom >= 0
  );
}
/**
 * get scrolled distance in percentage
 * @param {HTMLElement} el
 * @returns {number}
 */
function getScrolledPercentage(el: Element) {
  const rect = el.getBoundingClientRect();
  const windowHeight =
    window.innerHeight || document.documentElement.clientHeight;
  const scrollHeight =
    window.pageYOffset || document.documentElement.scrollTop;
  const elementTop = rect.top + scrollHeight;
  const elementBottom = elementTop + el.clientHeight;
  const scrolledDistance = elementBottom - scrollHeight;
  const totalDistance = el.clientHeight + windowHeight;
  const scrolledPercentage = (scrolledDistance / totalDistance) * 100 * -1 + 100;

  return scrolledPercentage;
}
tilesScrollEffect();
document.addEventListener("scroll", (e) => {
  tilesScrollEffect();
});

function tilesScrollEffect() {
  const tiles = document.querySelectorAll(".tile");
  tiles.forEach((tile) => {
    if (isInViewport(tile)) {
      // get scrolled distance with getScrolledDistance function
      const scrolledDistance = getScrolledPercentage(tile);

      tile.innerHTML = "Scrolled Distance: " + scrolledDistance.toFixed(2) + " %"
    }
  });
}
Scrolled Distance: JS %