aboutsummaryrefslogtreecommitdiff
path: root/public/javascripts/scrollSnap.js
blob: 67e3e0a0fecbf1e9c741eb7f876283dbe409efe2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require('smoothscroll-polyfill').polyfill()

const self = {}
const schedule = require('./schedule')

self._nodes = {
  search: document.querySelector('#search'),
  weekSelector: document.querySelector('#week-selector')
}

self._timeoutID = null

self._handleDoneScrolling = function () {
  console.log('done scrolling!')
  const scrollPosition = document.body.scrollTop
  const weekSelectorHeight = self._nodes.weekSelector.clientHeight - self._nodes.search.clientHeight
  if (scrollPosition < weekSelectorHeight && scrollPosition > 0) {
    window.scroll({ top: weekSelectorHeight, left: 0, behavior: 'smooth' })
  }
}

self._handleScroll = function () {
  if (self._timeoutID != null) window.clearTimeout(self._timeoutID)
  self._timeoutID = window.setTimeout(self._handleDoneScrolling, 500)

  const scrollPosition = document.body.scrollTop
  const weekSelectorHeight = self._nodes.weekSelector.clientHeight - self._nodes.search.clientHeight
  if (scrollPosition >= weekSelectorHeight) {
    document.body.classList.add('week-selector-not-visible')
  } else {
    document.body.classList.remove('week-selector-not-visible')
  }
}

self._handleWindowResize = function () {
  const weekSelectorHeight = self._nodes.weekSelector.clientHeight - self._nodes.search.clientHeight
  const extraPixelsNeeded = weekSelectorHeight - (document.body.clientHeight - window.innerHeight)
  if (extraPixelsNeeded > 0) {
    document.body.style.marginBottom = `${extraPixelsNeeded}px`
  } else {
    document.body.style.marginBottom = null
  }
}

self.startListening = function () {
  window.addEventListener('scroll', self._handleScroll)
}

schedule.on('load', self._handleWindowResize)
window.addEventListener('resize', self._handleWindowResize)
module.exports = self