두 요소 스크롤 동기화

const box1 = document.getElementById('box1')
const box2 = document.getElementById('box2')

let isSyncing = false

function syncScroll(source, target, sourceWidth, targetWidth) {
  const ratio = source.scrollLeft / (source.scrollWidth - sourceWidth)
  target.scrollLeft = ratio * (target.scrollWidth - targetWidth)
}

box1.addEventListener('scroll', () => {
  if (!isSyncing) {
    isSyncing = true
    syncScroll(box1, box2, 1280, 640)
    isSyncing = false
  }
})

box2.addEventListener('scroll', () => {
  if (!isSyncing) {
    isSyncing = true
    syncScroll(box2, box1, 640, 1280)
    isSyncing = false
  }
})

isSyncing 플래그로 무한 이벤트 루프 방지

#532

hash 링크로 연결될 경우 스크롤위치가 최상단으로 위치하기 때문에 문제(헤더가 고정일 경우)가 있을수도 있어서 scroll-margin-top으로 제어가 가능한 부분을 설명하고 있다.


Footnotes

  1. 2ex 유닛을 사용하여 선택한 글꼴의 x 높이의 상대적인 크기로 설정.

#87