JSFiddle - React, Tailwind, and code Playground
HTML
<div class="lg">1</div>
<div class="lg">2</div>
<div class="lg">3</div>
<div class="lg">4</div>
<div class="lg" id="x">5</div>
CSS
.lg {
width: 400px;
border: 4px solid teal;
margin: 10px;
font-size: 3rem;
text-align: center;
padding: 140px 0;
}
JavaScript
const myElement = document.getElementById("x");
const doSomething = (entries, observer) => {
entries.forEach(entry => {
if (entry.target === myElement && entry.intersectionRatio >= 0.90) {
// The element is now fully visible
console.log("Element is visible.")
// Stop listening for intersection changes
observer.disconnect();
}
});
}
let observer = new IntersectionObserver(doSomething, {
root: null,
rootMargin: '0px',
threshold: 0.90,
});
observer.observe(myElement)
myElement.scrollIntoView({ behavior: "smooth", block: "end" });