-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (63 loc) · 2.18 KB
/
index.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* *******************
BASIC VARIABLES
** ******************/
var navBar = document.getElementById('nav-bar');
var activeClass = 'nav-link-active';
/* *******************
GET THE CLOSEST ANCESTOR OF THE EL WHICH MATCHES THE SELECTOR
** ******************/
function getTheClosest(el, selector) {
var elParent = el.parentElement;
while(el && elParent) {
if (elParent === elParent.parentElement.querySelector(selector)) {
return elParent;
} else {
elParent = elParent.parentElement;
}
}
return null;
}
/* *******************
ADD ACTIVECLASS TO ACTIVE NAV-LINK AND REMOVE IT FROM OTHER NAV-LINKS
** ******************/
function activateNavLink(activeLink) {
let activeLinkId = activeLink.getAttribute('id');
let theClosestNav = getTheClosest(activeLink, 'nav');
let notActiveLinks = theClosestNav.querySelectorAll('a:not([id=' + activeLinkId + '])');
activeLink.classList.add(activeClass);
notActiveLinks.forEach(notActiveLink => {
notActiveLink.classList.remove(activeClass);
});
}
/* *******************
CALL THE ABOVE FUNCTION IF CLICK NAV-LINK
** ******************/
navBar.addEventListener('click', function(event) {
if(event.target && event.target.nodeName === 'A') {
let navLink = event.target;
activateNavLink(navLink);
}
})
/* *******************
ACTIVATE NAV-LINK IF ITS CONTENT IS ON WINDOW
** ******************/
function scroll(content) {
const windowHeight = window.innerHeight;
const scrollEffectHeight = content.offsetTop - windowHeight / 2;
let navLinkHref = '#' + content.getAttribute('id');
let navLink = navBar.querySelector('a[href="' + navLinkHref + '"]');
if(document.body.scrollTop > scrollEffectHeight || document.documentElement.scrollTop > scrollEffectHeight) {
activateNavLink(navLink);
} else {
navLink.classList.remove(activeClass);
}
}
/* *******************
CALL THE ABOVE FUNCTION IF SCROLL DOWN
** ******************/
window.addEventListener('scroll', function() {
let sections = document.querySelectorAll ('.main section');
sections.forEach(section => {
scroll(section);
});
})