개발

Intersection Observer API #1 정의

dohye1 2022. 11. 10. 10:49
반응형

회사 프로젝트를 진행하면서 무한스크롤 구현할때 Intersection oberver를 사용해서 구현했다.

그런데 무한스크롤을 구현하는 예시를 보고 참고한거라, 정확한 동작방식에 대한 이해없이 무작정 사용했었기때문에 한번 정리를 해보고자 한다.

Intersection Observer 란?

타겟 요소와 상위 요소 또는 최상위 document의 viewport 사이의 intersection 내의 변화비동기적으로 관찰하는 방법이다.

  • Intersection Observer는 그들이 감시하고자하는 요소(target)가 다른요소(root)에 들어가거나 나갈때 또는 요청한 부분만큼 두 요소의 교차부분이 변경될때마다 실행될 콜백함수를 등록할 수 있게 한다.
  • 정확히 몇 픽셀이 겹쳐졌는지는 감지할 수 없고, 몇퍼센트정도 교차하는지를 감지할 수 있는것이다.
  • 대상 요소의 가시성이 변경될때마다 등록한 콜백함수를 실행한다.
  • root와 target 요소가 교차하는 정도를 intersection ratio라고 한다. 이 값은 target의 가시성 비율을 0 ~ 1.0의 숫자로 표현한다.

예시

intersection observer를 생성하기 위해서는 생성자 호출 시 콜백함수를 제공해야한다.

이 콜백함수는 target과 root가 교차할 때 실행된다.

let options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0 // 대상 요소가 root에 지정된 요소 내에서 100% 보여질때 콜백이 호출된다.
}

let observer = new IntersectionObserver(callback, options);

options

그럼 options 객체를 살펴보자

IntersectionObserver 생성자에 전달되는 options 객체는 observer 콜백이 호출되는 상황을 조작한다.

 

1. root

    대상이 되는 객체의 조상 요소여야한다.

    기본값은 브라우저 뷰포트이고, root값이 null이거나 지정되지 않았을때 기본값으로 설정된다.

 

2. rootMargin

    root가 가진 여백이다.

    이것은 root요소의 각 측면의 bouding box를 수축시키거나 증가시키며, 교차성을 계산하기전에 적용된다.

    기본값은 0이다.

 

3. threshold

    observer의 콜백이 실행될 대상 요소의 가시성 비율을 나타내는 단일 숫자 혹은 숫자 배열이다. 

    만약 50%만큼 요소가 보여졌을때를 탐지하고싶다면, 값을 0.5로 설정하면 된다.

    또는 25% 단위로 요소의 가시성이 변경될때마다 콜백이 실행되게 하고싶다면 [0, 0.25, 0.5, 0.75, 1] 과 같은 배열을 설정하면 된다.

    기본값은 0이고(요소가 1픽셀이라도 보이자마자 콜백이 실행됨), 1.0은 요소의 모든 픽셀이 화면에 노출되기 전에는 콜백을 실행시키지      않음

 

엘리먼트를 target으로 등록하기

const wrapper = document.getElementById("wrapper");
const target = document.getElementById("target");

const callback = (entries, observer) => {
  console.log(entries, observer);
};

const observer = new IntersectionObserver(callback, {
  threshold: 0.4,
});

observer.observe(target);

감시할 엘리먼트를 observer에 등록하려면

observer.observe(target);

이렇게 해주면 된다!

그래서 콘솔로 출력을 해보면 2개의 객체가 출력된다.

 

callback

callback이 받는 값들을 살펴보자

 

1. entries

우선 entries를 보면 observer의 등록한 target의 정보가 배열로 들어있다.

그래서 각 entry의 리스트를 반환한다.

 

만약 observer에 2개의 target을 설정해주었을때 2개의 target이 root에 동시에 노출이 되면, entries의 길이는 2가 되는것이다!

 

entry가 가진 값들을 보면

entry.boundingClientRect
entry.intersectionRatio
entry.intersectionRect
entry.isIntersecting
entry.rootBounds
entry.target
entry.time

IntersectionObserverEntry.boundingClientRect 

target 엘리먼트를 반환한다.

 

IntersectionObserverEntry.intersectionRatio

얼마나 겹치는지에 대한 비율을 알려주는듯!

 

IntersectionObserverEntry.intersectionRect

현재 target이 root에 노출되어있는 정보를 보여줌!

아래의 값들을 보여준다.

내가 target의 높이를 100으로 설정해뒀는데, 아래에서 찍히는 height가 50으로 나온다.

즉, root에서 보여지는 target 정보만 보여진다!

IntersectionObserverEntry.isIntersecting

root와 target이 intersect 되고 있는지 boolean으로 알려준다.

만약 true라면, intersecting이 되었다는 의미이다.

만약 false라면 intersecting에서 not-intersecting이 된것이다.

 

IntersectionObserverEntry.rootBounds

root에 대한 정보를 담고있다.

IntersectionObserverEntry.target 

Element 타입으로 target의 정보를 보여준다.

 

IntersectionObserverEntry.time

A DOMHighResTimeStamp indicating the time at which the intersection was recorded, relative to the IntersectionObserver's time origin.

 

2. observer

intersection observer의 옵션을 보여주는것같다!

 

다음 포스트는 실습예제를 작성해보겠다!

 

 

참고

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry