-
Notifications
You must be signed in to change notification settings - Fork 0
/
func.js
66 lines (53 loc) · 1.73 KB
/
func.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
55
56
57
58
59
60
61
62
63
64
65
66
window.addEventListener('load', init)
function init() {
const adjust = window.innerHeight/2;
const sections = [];
const navItems = document.querySelectorAll("#navbar a");
var csIndex = undefined;
console.log(adjust);
document.querySelectorAll("section").forEach((section) => {
let sectionTop = section.offsetTop;
let sectionBottom = sectionTop + section.clientHeight;
sections[sections.length] = {top: sectionTop, bottom: sectionBottom, hash: '#'+section.getAttribute("id")}
});
window.addEventListener("scroll", (e) => {
if(undefined!=csIndex && window.scrollY + adjust> sections[csIndex].top && window.scrollY + adjust < sections[csIndex].bottom )
{
return;
}
sections.forEach((section, index) => {
if (window.scrollY + adjust > section.top && window.scrollY +adjust < section.bottom)
csIndex = index;
});
if(csIndex == undefined )
return;
document.querySelector('#navbar a.active')?.classList.remove('active');
navItems.forEach( (nav) => {
let url = new URL(nav.href);
if ( url.hash == sections[csIndex].hash )
nav.classList.add('active');
});
});
document.querySelectorAll('a').forEach( (node) => {
node.addEventListener('click', (e) => {
let url = new URL(e.target.href);
if (window.location.hostname != url.hostname ||
window.location.pathname != url.pathname ||
!url.hash
) {
return;
}
e.preventDefault();
scrollTo(url.hash)
});
});
function scrollTo(elemId)
{
let toPos = document.getElementById(elemId.substr(1))?.offsetTop;
window.scrollTo({
top: toPos,
left: 0,
behavior: 'smooth'
});
}
}