-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscroll-handler.js
35 lines (28 loc) · 1.06 KB
/
scroll-handler.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
const debounce = (fn = Function.prototype, delay = 0) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(fn, delay, ...args);
};
};
const menuItems = [...document.querySelectorAll('.nc-menu-item')]
.reduce(
(items, item) => items.set(item.hash.slice(1), item),
new Map()
);
const pageSet = new Set(document.querySelectorAll('.pc-page'));
const markActiveMenuItem = () => {
const { width, height } = window.visualViewport;
const elements = document.elementsFromPoint(width / 2, height / 2);
elements.some(el => {
if (pageSet.has(el)) {
const classList = menuItems.get(el.id).classList;
if (!classList.contains('hover')) {
menuItems.forEach(item => item.classList.remove('hover'));
classList.add('hover');
}
}
});
};
addEventListener('load', markActiveMenuItem);
addEventListener('scroll', debounce(markActiveMenuItem, 50));