-
Notifications
You must be signed in to change notification settings - Fork 0
/
header-auto-hide-on-vertical-scroll.js
49 lines (45 loc) · 1.51 KB
/
header-auto-hide-on-vertical-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
export function headerAutoHideOnVerticalScroll(isNavOpen) {
const header = document.querySelector("header");
const supportPageOffset = window.pageXOffset !== undefined;
const isCSS1Compat = (document.compatMode || "") === "CSS1Compat";
let previousScrollPosition = 0;
const isScrollingDown = () => {
let scrolledPosition = supportPageOffset
? window.pageYOffset
: isCSS1Compat
? document.documentElement.scrollTop
: document.body.scrollTop;
const isScrollDown = scrolledPosition > previousScrollPosition;
previousScrollPosition = scrolledPosition;
return isScrollDown;
};
const handleNavScroll = () => {
if (isNavOpen()) {
return;
}
if (isScrollingDown()) {
header.classList.add("scroll-down");
header.classList.remove("scroll-up");
} else {
header.classList.add("scroll-up");
header.classList.remove("scroll-down");
}
};
let throttleTimer;
const throttle = (callback, time) => {
if (throttleTimer) {
return;
}
throttleTimer = true;
setTimeout(() => {
callback();
throttleTimer = false;
}, time);
};
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
window.addEventListener("scroll", () => {
if (mediaQuery && !mediaQuery.matches) {
throttle(handleNavScroll, 250);
}
});
}