JavaScript - Intersection Observer API

Moolbum·2022년 8월 11일
0

JavaScript

목록 보기
15/18
post-thumbnail

Intersection Observer의 사용법



1. new IntersectionObserver() 생성

new IntersectionObserver()를 통해 생성한 인스턴스 io는 관찰자를 초기화하고 관찰 대상 target을 지정합니다.

  • callback : 조건이 되면 실행되는 콜백함수
  • option : 관찰자 옵션
  • target : 관찰할 대상 등록
const target = document.querySelector('.item');
const options = {...}
const callback = (entries, observer) => {...}
const io = new IntersectionObserver(callback, options)
io.observe(target);

2. option 설정

new IntersectionObserver에 들어갈 인자중 하나인 option은 교차의 기준을 정합니다.

  • root : 교차되는기준이 되는 요소입니다. 기본값은 viewport 입니다.
  • rootMargin : 일반 margin과 동일하게 적용할 수 있고 -값도 가능합니다.
  • threshold : 엘리먼트의 가시성 여부를 판단하기 위한 값으로 0~1값이다. 숫자가 클수록 엘리먼트가 많이 보여진다는 것을 뜻한다.
    ex) 0.8: 80% 노출되면 실행, 1: 100% 다 노출되면 실행
const target = document.querySelector('.item');
const options = {
  root: document.querySelector('#scrollArea'),
  //root: null, // 기본값인 view
  rootMargin: '0px',
  threshold: 7 // 70 퍼센트 보였을 때
}

const io = new IntersectionObserver(callback, options)

3. callback 설정

타겟 엘리먼트가 교차 되었을 때 실행되는 함수입니다.
2개의 인자 (entries, observer)를 가지고있습니다.

  • observer: 콜백함수가 호출되는 IntersectionObserver
  • entries: IntersectionObserverEntry인스턴스의 배열입니다. 읽기전용 속성이며 아래 속성들을 가지고 있습니다.
    • isIntersecting : 관찰 대상과의 교차상태 (boolean)
    • boundingClientRect : 관찰 대상의 사각형정보 {top,bottom...}
    • target : 관찰 대상 요소 (element)
    • time : 변경이 발생한 시간 정보
    • rootBounds : 지정한 루트 요소의 사각형 정보
    • target : 관찰 대상 요소 (element)
const callback = (entries, observer) => {...}
const io = new IntersectionObserver(callback, options)

callback 함수내부

const callback = (entries, observer) => {
	entries.forEach(entry => {
    	if(entry.isIntersecting){ // 교차가 되었을때 true
          console.log(entry); // 교차가 되었을때 로직 추가
          observer.unobserve(entry.target); // 관찰 해제로 한번만 실행
        }
    })
}
const io = new IntersectionObserver(callback, options)

4. IntersectionObserver methods

  • observe() : 요소의 관찰을 시작합니다.
  • unobserve() : 요소의 관찰을 중단합니다.
  • disconnect() : 인스턴스가 관찰하는 모든 가시성 변화 주시 대상을 해제합니다.
const target = document.querySelector('.item');
const options = {...}
const callback = (entries, observer) => {...}
const io = new IntersectionObserver(callback, options)
io.observe(target);
//io.unobserve(target);
//io.disconnect(target);
profile
Junior Front-End Developer 👨‍💻

0개의 댓글