[JavaScript] IntersectionObserver

전홍석·2025년 8월 6일

javascript

목록 보기
8/11
post-thumbnail

IntersectionObserver

IntersectionObserver 은 JS의 Web API 중 하나로, 브라우저에서 기본으로 제공하는 표준 내장 객체이다

scroll 위치에 따라 어떤 요소가 viewport 안에 들어왔는지 자동 감지한다
이는 DOM 요소와 viewport 간의 교차 상태를 비동기로 추적한다

활용예시

  • 사용자가 scroll로 특정 섹션에 도달했는지 감지
  • lazy loading 이미지 처리
  • 특정 요소 화면 진입 시 애니메이션 발동

기본 문법

const observer = new IntersectionObserver(callback, options)
observer.observe(targetElement)

callback 함수

타겟 요소가 뷰포트에 들어오거나 나갈때 자동으로 호출

(entries, observer) => {
	entries.forEach(entry => {
    	if (entry.isIntersecting) {
        	console.log("요소가 보임")
        }
    })
}
  • entries : 감지된 요소들 배열
  • entry.isIntersecting : 요소가 보이는지 true, false로 알려줌

options 객체

옵저버의 동작 방식을 설정하는 옵션 객체

{
	root : null, // 기준 요소 (null 이면 뷰포트)
    rooMargin: "0px", // 기준 요소에서 얼마나 margin을 둘지
    threshold: 0.5 // 0~1 사이의 값 (0.5 이면 50% 이상 보여야 감지)
}

observe, unobserve

observer.observe(targetElement) //감지 시작
observer.unobserve(targetElement) // 감지 중단
const callback = (entries) => {
	entries.forEach(entry => {
    	if (entry.isIntersecting) console.log("보임", entry.target)
        else console.log("안보임", entry.target)
    })
}

const options = {
	threshold: 0.5
}

const observer = new Intersection(callback, options)

const section = document.querySelector("#section")
observer.observe(section)

IntersectionObserver 는 scroll 이벤트 없이도 요소의 노출 여부를 감지할 수 있기 때문에 성능이 좋고 효율적인 방법이다

profile
취뽀까지 숨참기

0개의 댓글