자바스크립트

[JavaScript] Scroll에 따른 progressbar 만들기

코딩하는둥이 2025. 3. 18. 17:23

스크롤를 아래로 내릴수록 위에 있는 프로세스 바가 색이 채워지는 걸 볼 수 있습니다. 

 

먼저 스크롤 이벤트를 주기 위해서 스크롤이 될때마다 onScroll이라는 함수가 실행되도록 합니.

;(function () {
  'use strict'

  const get = (target) => {
    return document.querySelector(target)
  }

  window.addEventListener('scroll', () => {
    onScroll()
  })
})()

 

height에 보여주는 영역을 제외한 나머지 스크롤 영역의 높이를 계산이 되어야하기 때문에 scrollHight - clientHight를 빼 줍니다. 스크롤 높이는 scrollTop를 통해 알 수 있습니다.

이 두 가지를 사용해서 나누고 100를 곱하게 되면 width를 구할 수 있습니다.

  const onScroll = () => {
    const scrollTop = document.documentElement.scrollTop
    const height =
      document.documentElement.scrollHeight -
      document.documentElement.clientHeight
    const scrollWidth = (scrollTop / height) * 100
    console.log(scrollWidth + '%');
  }

 

동영상 보면 알다시피 height 값을 알 수 있습니다.

 

 

 일정한 주기마다 이벤트를 발생시키는 방법인 throttle를 적용시키겠습니다.

const throttle = (callback, time) => {
if (timerId) return
timerId = setTimeout(() => {
  callback()
  timerId = undefined // 초기화
}, time)
}

 

window.addEventListener('scroll', () => {
    throttle(onScroll, 100)	
})

 

이렇게 코드를 짜면 스크롤에 따른 progressbar를 생성했습니다!

;(function () {
  'use strict'

  let timerId

  const get = (target) => {
    return document.querySelector(target)
  }

  const $progressBar = get('.progress-bar')

  const throttle = (callback, time) => {
    if (timerId) return
    timerId = setTimeout(() => {
      callback()
      timerId = undefined
    }, time)
  }

  const onScroll = () => {
    const scrollTop = document.documentElement.scrollTop
    const height =
      document.documentElement.scrollHeight -
      document.documentElement.clientHeight
    const scrollWidth = (scrollTop / height) * 100
    $progressBar.style.width = scrollWidth + '%'
  }

  window.addEventListener('scroll', () => {
    throttle(onScroll, 100)
  })
})()

'자바스크립트' 카테고리의 다른 글

[JavaScript] 이미지 슬라이드  (0) 2025.03.20
[JavaScript] 무한 스크롤 만들기  (0) 2025.03.19
[JavaScript] 클래스  (0) 2025.03.17
[JavaScript] 프로토타입  (0) 2025.03.14
[JavaScript] 함수  (0) 2025.03.07