JSFiddle - React, Tailwind, and code Playground
by nadalc
HTML
<div class="viewport">
<div class="element">before scroll</div>
<div class="observed">after scroll</div>
</div>
CSS
.viewport {
height: 200px;
background-color: blue;
overflow-y: scroll;
padding: 16px;
}
.element {
height: 300px;
background-color: red;
}
.observed {
height: 100px;
background-color: green;
}
JavaScript
// // Intersection Observer V1
// const logIfIsInViewPort = (entries) => {
// for (const entry of entries) {
// if (entry.isIntersecting) {
// console.log(entry);
// }
// }
// };
//
// const observer = new IntersectionObserver(logIfIsInViewPort);
// observer.observe(document.querySelector('.observed'));
// Intersection Observer V2
const handler = (changes) => {
for(const change in changes) {
// feature detection
if(typeof change.isVisible !== 'undefined') {
if(change.isIntersecting && change.isVisible) {
console.log(`Visible since ${change.time}`);
} else {
// fallback to v1 if not supported
change.isVisible = true;
console.log(`v2 not supported, fallback to v1`);
}
}
}
}
const observer = new IntersectionObserver(handler, {
threshold: [1.0],
trackVisibility: true, // this will give you the isVisible property
delay: 100
});
observer.observe(document.querySelector('.observed'));