Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Created April 30, 2021 20:45
Show Gist options
  • Save GGrassiant/0abc01e04523a0d09eaf059a4978fa59 to your computer and use it in GitHub Desktop.
Save GGrassiant/0abc01e04523a0d09eaf059a4978fa59 to your computer and use it in GitHub Desktop.
Simple Intersection Observer
<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));
@GGrassiant
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment