-
Notifications
You must be signed in to change notification settings - Fork 0
/
scroll.js
54 lines (38 loc) · 1.52 KB
/
scroll.js
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
52
53
54
function scrollAnimation (getState) {
const { currentPosition, hasReachedEnd } = getState();
window.scroll(0, currentPosition);
if (!hasReachedEnd) {
requestAnimationFrame(() => scrollAnimation(getState), 1000 / 60)
}
}
const updateScroll = (isDirectionFromTop, state, setCurrentPositionAsEnd) => () => {
const { step, currentPosition, end } = state;
state.currentPosition = isDirectionFromTop ? currentPosition + step : currentPosition - step;
state.step += 1;
state.hasReachedEnd = isDirectionFromTop ? currentPosition >= end : currentPosition <= end;
const isScrollBeyondEnd = isDirectionFromTop ? currentPosition > end : currentPosition < end;
setCurrentPositionAsEnd(isScrollBeyondEnd);
return state;
}
function scrollState(section, smooth = true) {
let currentPosition = window.scrollY || window.pageYOffset
let end = currentPosition + section.getBoundingClientRect().top - 70;
if (!smooth) return () => end;
let step = 30.0;
function setCurrentPositionAsEnd(condition) {
if (condition) this.currentPosition = this.end;
}
const state = { currentPosition, end, step };
return updateScroll(currentPosition < end, state, setCurrentPositionAsEnd.bind(state));
}
function scrollToSection(id, smooth = true) {
if (!id) return;
const section = document.querySelector(id);
const getState = scrollState(section, smooth);
if (smooth) {
requestAnimationFrame(() => scrollAnimation(getState), 1000 / 60);
} else {
window.scrollTo(0, getState());
}
}
export { scrollToSection };