Intersecting
Not Intersect

Intersection Observer

Ridho Anandamal

22 March 20232 minutes

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

This playground using Vue

How to Create it

Lets create initital structure HTML.

index.html
<div class="parent">
  <div class="container">
    <div class="box box-1" ref="box1">Object</div>
  </div>
  <div class="container">
    <div class="box box-2" ref="box2">Object</div>
  </div>
</div>

Then add javascript to observer box class

index.ts
const box1 = ref<HTMLDivElement | null>(null);
const box2 = ref<HTMLDivElement | null>(null);

onMounted(() => {
  const observer = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.textContent = "Intersecting";
          return entry.target.classList.add("intersecting");
        }
        entry.target.textContent = "Not Intersect";
        entry.target.classList.remove("intersecting");
      });
    },
    { rootMargin: "-15% 0px -15% 0px" }
  );
  observer.observe(box1.value!);
  observer.observe(box2.value!);

  onUnmounted(() => {
    // Dont forget to disconnect/unobserver when not use
    observer.disconnect(); // All element
  });
});

Then we add style and class intersecting for object got intersection observer

style.css
.parent {
  width: 100%;
  height: 100%;
  overflow: scroll;
}
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box {
  width: 200px;
  height: 100px;
  background-color: white;
  color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
} /* this style used when intersecting */
.box-1.intersecting {
  color: white;
  background-color: rgb(56, 135, 246);
}
.box-2.intersecting {
  color: white;
  background-color: rgb(243, 76, 76);
}