-
Notifications
You must be signed in to change notification settings - Fork 0
/
scroll.js
36 lines (26 loc) · 1.11 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
// The debounce function receives our function as a parameter
const debounce = (fn) => {
// This holds the requestAnimationFrame reference, so we can cancel it if we wish
let frame;
// The debounce function returns a new function that can receive a variable number of arguments
return (...params) => {
// If the frame variable has been defined, clear it now, and queue for next frame
if (frame) {
cancelAnimationFrame(frame);
}
// Queue our function call for the next frame
frame = requestAnimationFrame(() => {
// Call our function and pass any params we received
fn(...params);
});
}
};
// Reads out the scroll position and stores it in the data attribute
// so we can use it in our stylesheets
const storeScroll = () => {
document.documentElement.dataset.scroll = window.scrollY;
}
// Listen for new scroll events, here we debounce our `storeScroll` function
document.addEventListener('scroll', debounce(storeScroll), { passive: true });
// Update scroll position for first time
storeScroll();