Simple Intersection Observer
Based on Amelie Benoit's post
Simple Intersection Observer
Based on Amelie Benoit's post
<html> | |
<body> | |
<main> | |
<div style="height: 100vh;border:1px solid red;" data-track-visible="1">Coucou</div> | |
<div style="height: 100vh;border:1px solid red;" data-track-visible="2">Coucou</div> | |
<div style="height: 100vh;border:1px solid red;" data-track-visible="3">Coucou</div> | |
<div style="height: 100vh;border:1px solid red;" data-track-visible="4">Coucou</div> | |
<div style="height: 100vh;border:1px solid red;" data-track-visible="5">Coucou</div> | |
</main> | |
<script src="./index.js"></script> | |
</body> | |
</html> |
const onObserve = entries => { | |
return entries.forEach(entry => { | |
if (entry.intersectionRatio > 0) { | |
const track_value = entry.target.dataset.trackVisible; | |
console.log(track_value, 'entered the view!'); | |
observer.unobserve(entry.target); | |
} | |
}); | |
}; | |
const observer = new IntersectionObserver(onObserve); | |
document.querySelectorAll("[data-track-visible]").forEach((el) => observer.observe(el)); |
https://dev.to/producthackers/intersection-observer-using-react-49ko