observeMutations로 HTML Element의 변화를 감지하자..

준영·2024년 1월 17일
0

코드 지갑..

목록 보기
20/20
import { onMounted, onUnmounted, ref, type Ref } from 'vue'

const useBottomScroll = (nodeId: string): Ref<boolean> => {
  const isBottom = ref<boolean>(false)
  let observer: MutationObserver

  const checkScroll = (): void => {
    const currentScrollVal = window.scrollY + window.innerHeight
    const bottomScrollVal = document.body.offsetHeight

    if (currentScrollVal >= bottomScrollVal) {
      isBottom.value = true
    } else {
      isBottom.value = false
    }

    console.log('isBottom', isBottom.value)
  }

  const observeMutations = (nodeId: string): void => {
    const targetNode: HTMLElement | null = document.getElementById(nodeId)
    if (targetNode === null) return

    observer = new MutationObserver(checkScroll)
    observer.observe(targetNode, { childList: true, subtree: true })
  }

  onMounted(() => {
    window.addEventListener('resize', checkScroll)
    window.addEventListener('scroll', checkScroll)
    setTimeout(() => {
      checkScroll()
      observeMutations(nodeId)
    }, 100)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', checkScroll)
    window.removeEventListener('scroll', checkScroll)
    observer.disconnect()
  })

  return isBottom
}

export default useBottomScroll
profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글