티스토리 뷰

IntersectionObserver 

어떤 요소가 화면의 영역과 교차하는지 관찰한다. ( 어떤 요소가 화면으로 들어오는지, 나가는지 확인 )

Intersection : 교차 / Observer : 관찰

const io = new IntersectionObserver(function (entries){
  entries.forEach(function (entry) {
    if(!entry.isIntersecting){
      return
    }
    console.log(entry.isIntersecting, entry.target)
  })
})

const h1Els = document.querySelectorAll('h1');
h1Els.forEach(function (el) {
  io.observe(el);  
})
  • target : 관찰 중인 요소
  • isIntersecting : 화면 안에 들어있는지
if(!entry.isIntersecting){
  return
}

👉 화면에서 벗어날 때는 로직을 끝내고, 화면에 들어올 때만 if 문 밖의 로직을 처리한다.

 

See the Pen Untitled by KIMAERI (@AERIKIM) on CodePen.

 

IntersectionObserver 사용하기

1️⃣ info 클래스의 요소들을 찾고, 그 요소들을 반복해서 io 객체의 observe 를 통해 요소를 관찰한다. 

const infoEls = docuemnt.querySelectorAll('.info')
infoEls.forEach(el => {
    io.observe(el)
})

 

2️⃣ 복수 개의 관찰 데이터 정보가 entries로 들어가며 개별적으로 처리하기 위해 forEach를 사용한다.
보이지 않을 때는 return 키워드로 함수를 사용하지 않고, 보일 때는 show 클래스를 추가해준다. 

const io = new IntersectionObserver(function (entries) {
    entries.forEach(entry => {
        if(!entry.isIntersecting){
            return
        }
        entry.target.classList.add('show');
    })
})

 

👉 처음에는 y축으로 100px 이동하고 불투명 상태로 두었다가, show 클래스가 추가되면 원래 위치로 돌아가며 요소가 나타난다.

.info {
  transition: 1s;
  transform: translate(0, 100px);
  opacity: 0;
}
.info.show {
  transform: translate(0, 0);
  opacity: 1;
}

 

 

출처

프론트엔드 웹 개발의 모든 것 초격차 패키지

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함