JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

HTML

Scroll down ;)
<div>I am the box</div>

CSS

div {
  width: 200px;
  height: 200px;
  margin: 1000px 0;
}

div {
  background: blue;
}

div.onscreen {
  background: red;
}

JavaScript

const box = document.querySelector("div");

function onIntersectionChange(entries) {
	for (const entry of entries) {
  	console.log(entry);

  	const element = entry.target;
    
    // Check if element has gone on screen or off screen:
    if (entry.isIntersecting) {
    	element.classList.add("onscreen");
    } else {
      element.classList.remove("onscreen");
    }
  }
}

const observer = new IntersectionObserver(onIntersectionChange, {
	threshold: 1.0 // Trigger only when the entire box is visible
});

observer.observe(box);