Intersection Observer demo

Quick test on how to use the IntersectionObserver, and what happens if we observe "body".

by David Iglesias

HTML

<div class="large">
Some lorem ipsum could go here, several tons of it, in fact!

But instead we make the div tall
</div>
<div id="observed" class="observed">
This is the div that is being observed
</div>
<div class="large">
Some more code below!
</div>

<div id="intersection_indicator" class="sticky"></div>

CSS

* { box-sizing: border-box; font-family: sans-serif; }
.large {
  min-height: 2000px;
  padding-right: 32px;
}
.observed {
  border: 2px solid red;
  width: 320px;
  height: 200px;
  margin: 32px auto;
}
.observed.intersecting {
  border-color: green;
}
.sticky {
  width: 32px;
  height: 32px;
  position: fixed;
  top: 0px; right: 0px;
  background-color: red;
}
.sticky.intersecting {
  background-color: green;
}

JavaScript

let observer = new IntersectionObserver((entries, observer) => {
	entries.forEach((entry) => {
    if (entry.isIntersecting) {
      intersection_indicator.classList.add('intersecting');
      observed.classList.add('intersecting');
    } else {
      intersection_indicator.classList.remove('intersecting');
      observed.classList.remove('intersecting');
    }
  });
});

observer.observe(observed);
// Try this
// observer.observe(document.body);