Window스크롤의 Bottom이 해당 Element의 bottom에 닿았는지 확인하는 방법

// window scroll의 bottom 을 구한다
// 최상단에서 스크롤이 얼마나 떨어져 있는지 값 + 뷰포트의 높이
const windowScrollBottom = document.documentElement.scrollTop + window.innerHeight;

///////////////////////////

// 해당 Element의 Rect를 가져온다.
const elemRect = document.querySelector('#elem').getBoundingClientRect();

// 현재 뷰 포트의 top에서 elem까지의 거리 + elem의 높이
// elemRect.bottom과 같다 (뷰 포트 top에서 elem의 bottom 까지의 거리)
// const elemBottom = elemRect.top + elemRect.height;
const elemBottom = elemRect.bottom;

// elemBottom이 뷰포트의 높이보다 작거나 같아지는 순간이 닿은 순간이다.
if (elemBottom <= window.innerHeight) {
}

// (응용)정확히 Elem 중앙에 도착했을 때를 원하면
const elemHalfHeight = elemRect.height / 2;
if (elemBottom - elemHalfHeight <= window.innerHeight) {
}

// 스크롤을 올려서 Elem이 안보이게 될 경우
if isNotVisibleElem = window.innerHeight < elemRect.top;

이 작업을 할 당시에는 이렇게 처리했지만 Web API의 IntersectionObserver를 사용하는게 제일 좋은 방법이다.

IntersectionObserver - Web API | MDN


ZungTa
Written by
ZungTa
ZungTa입니다.

GitHub