JavaScript

Intersection Observer

fromslow 2021. 5. 20. 18:13

Intersection Observer API는 대상 요소와 상위 요소 또는 최상위 문서의 뷰포트의 교차점에서 변경 사항을 비동기식으로 관찰하는 기능이다.

 

즉, 기본적으로 뷰포트를 기준으로 화면에 요소가 보이는지의 여부를 구별할 수 있는 기능이다.

원하는 요소가 특정한 영역에 들어왔을 때 알려주는 관찰자이다.

 

 

IntersectionObserver 클래스가 생성될 때 callback 함수와 options 인자가 필요하다.

let observer = new IntersectionObserver(callback, options);

 

 

 

 

callback

요소가 영역에 들어올 때 호출되는 콜백 함수이다.

콜백 함수의 인자로 entries와 observer를 받는다.

let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};

entries는 뷰포트 내 요소들의 배열을 뜻한다.

 

 

entries는 다음과 같은 속성을 가진다.

 

-boundingClientRect(읽기전용): Element.getBoundingClientRect와 동일. 해당 요소의 위치를 반환한다.

 

-intersectionRatio: 관찰 대상의 교차한 영역 백분율(intersectionRect 영역에서 boundingClientRect 영역까지 비율, Number).

쉽게 말하면 뷰포트를 기준으로 해서 화면에 들어와있는 요소의 비율.

0~1사이의 값을 반환한다.

 

-isIntersecting(Boolean): 관찰 대상의 교차 상태. 화면에 들어와 있으면 true, 화면 밖으로 나가 있으면 false 반환

 

-target: 관찰 대상 요소

 

 

 

이외의 속성은 여기에서 확인할 수 있다.

 

 

 

-

 

 

 

options (선택)

콜백이 호출되는 상황을 제어할 수 있는 객체이다.

let options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

-root: 뷰포트로 사용되는 요소. 뷰포트(윈도우창)이 기본이며, 이 때는 querySelector 대신 null을 쓴다.

 

-rootMargin: root에 margin을 주어서 조정하는 용도. css의 margin과 동일하다.

 

-threshold: 콜백이 실행되어야 하는 비율을 지정하는 용도.

0부터 1사이에서 지정한다.

예를 들어 0.3이면 요소가 0.3만큼 들어왔을 때 콜백이 실행된다.