-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathscroll.js
More file actions
50 lines (43 loc) · 1.5 KB
/
Copy pathscroll.js
File metadata and controls
50 lines (43 loc) · 1.5 KB
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
// animated scrolling because Safari can't do it natively
const easeInOutQuad = (t, b, c, d) => {
let t2 = t / (d / 2)
if (t2 < 1) return (c / 2) * t2 * t2 + b
t2 -= 1
return (-c / 2) * (t2 * (t2 - 2) - 1) + b
}
export const scrollToElement = (elementId, duration) => {
const to = elementId ? document.getElementById(elementId).offsetTop - 80 : 0
const parent = document.scrollingElement || document.documentElement
const start = parent.scrollTop
const change = to - start
const startDate = +new Date()
const animateScroll = () => {
const currentDate = +new Date()
const currentTime = currentDate - startDate
parent.scrollTop = parseInt(easeInOutQuad(currentTime, start, change, duration), 10)
if (currentTime < duration) {
requestAnimationFrame(animateScroll)
} else {
parent.scrollTop = to
}
}
animateScroll()
}
export const scrollToPosition = (position, duration) => {
// position is target height calculated from top of the page
const parent = document.scrollingElement || document.documentElement
const start = parent.scrollTop
const change = position - start
const startDate = +new Date()
const animateScroll = () => {
const currentDate = +new Date()
const currentTime = currentDate - startDate
parent.scrollTop = parseInt(easeInOutQuad(currentTime, start, change, duration), 10)
if (currentTime < duration) {
requestAnimationFrame(animateScroll)
} else {
parent.scrollTop = position
}
}
animateScroll()
}