JSFiddle - React, Tailwind, and code Playground
CSS
body {
background-color: white;
transition: background-color 0.5s ease;
}
div {
display: block;
clear: both;
width: 90%;
height: 50vh;
margin: 10vh auto;
}
JavaScript
let numberOfDivs = 5;
function createDiv(divNumber) {
// set the div's tag name, class name and a unique ID
let aDiv = document.createElement('div');
aDiv.className = 'my-divs';
aDiv.id = 'div' + divNumber;
// set a random hex bg colour for the div;
// drops a leading zero 1/16 of the time but it's not material to the example
aDiv.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
document.body.appendChild(aDiv);
// set IntersectionObserver on the div
let observer = new IntersectionObserver(whatsIn, {threshold: 0.5});
observer.observe(aDiv);
}
// create the divs
for ( let i = 0; i < numberOfDivs; i++ ) {
let newDiv = createDiv(i);
}
// examine the IntersectionObserver output whenever isIntersecting changes
function whatsIn(payload) {
console.log("Is " + payload[0].target.id + " intersecting? " + payload[0].isIntersecting);
// change background color based on most recent intersection true
document.body.style.backgroundColor =
payload[0].isIntersecting
? payload[0].target.style.backgroundColor
: document.body.style.backgroundColor;
}