JSFiddle - React, Tailwind, and code Playground

by Federico Tibaldo

HTML

<div id="target"><p id="target-intersection-ratio">0%</p></div>

CSS

#target {
  margin: 1000px 0;
  height: 1000px; /* Update to preview different behaviors */
  background-color: red;
  width: 100%;
  visibility: hidden;
}

#target-intersection-ratio {
  position: sticky;
  top: 0;
}

JavaScript

const target = document.getElementById('target');
const targetIntersectionRatio = document.getElementById('target-intersection-ratio');

const buildThresholdList = () => {
	const step = 1;
  const thresholds = [];
  for (let threshold = 0; threshold <= 100; threshold += step) {
  	thresholds.push(threshold / 100);
	}
  return thresholds;
}

const onIntersection = ([entry]) => {
	const ratio = `${entry.intersectionRatio * 100}%`;
	targetIntersectionRatio.textContent = ratio;
  console.log(ratio);
}

const intersectionObserver = new IntersectionObserver(onIntersection, { threshold: buildThresholdList() });

intersectionObserver.observe(target);