[프로그레스 바] progressbar 구현

youngseo·2022년 3월 2일
0

JS프로젝트

목록 보기
12/18
post-thumbnail

프로그레스 바(Progressbar) 구현

1. 기본 틀 생성

;
(function () {
  'use strict'

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

})()

2. 스크롤 이벤트 생성

;
(function () {
  'use strict'

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

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

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

  window.addEventListener('scroll', () => onscroll())
})()

3. throttle 적용

;
(function () {
  'use strict'

  let timerId


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

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

0개의 댓글