IntersectionObserver

Using Intersection Observer, we can observe the visibility change of an element(target) in the viewport(screen visible area).

The most important use cases of Intersection Observer are Lazy Loading and Infinite Loading of images. Before the introduction of Intersection Observer, we will try to find the visibility of an element by binding the scroll event and when the scroll event is triggered, you will check if an element is in the visible viewport.

The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. This way, sites no longer need to do anything on the main thread to watch for this kind of element intersection, and the browser is free to optimize the management of intersections as it sees fit.


RESETRUNFULL
<!DOCTYPE html><html><body>
<div style="height:200px !important; overflow-y:scroll;">
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
   <p>Hello</p>
</div>
<script>
   let observerConfig = {
      root: null,          // document, ie. screen viewport
      rootMargin: '0px',
      threshold: 1.0       // invoked only when completely visible
   };
   function observerFn(entries, observer) {
      const e = entries[0];
      e.target.innerHTML = "Hello World";
   }
   let observer = new IntersectionObserver(observerFn, observerConfig);
   document.querySelectorAll("p").forEach(p=>observer.observe(p));
   // observer.unobserve(document.querySelector("p"));
   // observer.disconnect().
</script></body></html>