Intersection Observer API

SUN·2024년 1월 11일

JS 함수

목록 보기
8/8

1. Intersection Observer API란?

원하는 특정요소를 target으로 설정하여 해당 target이 상위 요소나 뷰포트와 교차할 때 변화를 비동기적으로 관찰한다.

2. Intersection Observer API의 사용

콜백 함수의 발동 조건

다음 상황에서 콜백 함수가 발동된다.

1) target이 뷰포트나 특정 요소와 교차할 때 (여기서 특정 요소는 root element 나 root로 부른다.)
2) observer가 처음으로 타겟 요소를 봤을 때

기본 문법

root : target과 교차할 기준이 되는 요소. 특정 요소와 교차를 하는 것이 아니라 디바이스의 뷰포트와 교차를 관찰할 때는 root에 null값을 지정한다.

threshold : threshold의 값은 root에서 지정된 요소에서 target이 설정한 값만큼 보일 때 콜백을 호출한다.

rootMargin : css의 마진과 유사한 값으로 root 요소과 교차할 면을 증가하거나 축소시킨다.

1) IntersectionObserver를 통해 observer를 생성한다.

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

let observer = new IntersectionObserver(callback, options);

2) 생성한 observer에 target 요소를 등록한다.

let target = document.querySelector("#listItem");
observer.observe(target);

3) observer가 target을 threshold에서 정한 교차지점에 도달했을 때 콜백을 실행한다.

아래에서 콜백 함수를 실행할 수 있다.

  • IntersectionObserverEntry에서 확인 할 수 있는 객체
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
  });
};

3. 예시

fnObserve()

function fnObserve() {

    let options = {
     	root: null,
        threshold: 0.2
    };
    
    const observer = new IntersectionObserver(observeCallback, options);

	document.querySelectorAll('.wrap').forEach(target => {
        observer.observe(target);
    });
    // 여러 요소가 있으면 각 요소들을 분해해준다.
    
}

function observeCallback (entries, observer) {
    entries.forEach(entry => {       

        const tar = entry.target;
        tar.classList.add('on');

        const title = tar.querySelector('.title');
        if (title) {
            title.classList.add('on');
        }

        const content = tar.querySelector('.content');
        if (content) {
            content.classList.add('on');
        }

        observer.unobserve(tar);
         // 엘리먼트가 화면에 보이지 않으면 함수 실행을 중단하고 더 이상 진행하지 않는다.
    });
}

참고

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

https://velog.io/@khy226/intersection-observer%EB%9E%80-feat-%EB%AC%B4%ED%95%9C-%EC%8A%A4%ED%81%AC%EB%A1%A4-%EB%A7%8C%EB%93%A4%EA%B8%B0#intersection-observer-%EC%82%AC%EC%9A%A9-%EB%B0%A9%EB%B2%95

https://moon-ga.github.io/javascript/intersectionobserver/

profile
안녕하세요!

0개의 댓글