-
Notifications
You must be signed in to change notification settings - Fork 361
/
Copy pathindex.js
68 lines (57 loc) · 1.94 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
const COMPONENT_SELECTOR = '[data-anchors-indicator]'
const ACTIVE_CLASS = 'data-active-class'
const SECTION_ATTR= 'data-sections'
const throttle = (fn, wait) => {
var time = Date.now()
return function() {
if ((time + wait - Date.now()) < 0) {
fn()
time = Date.now()
}
}
}
export default () => {
const components = document.querySelectorAll(COMPONENT_SELECTOR)
components.forEach(component => {
const sectionSelector = component.getAttribute(SECTION_ATTR)
const activeClass = component.getAttribute(ACTIVE_CLASS)
const sections = document.querySelectorAll(`${sectionSelector}`)
const allLinks = component.querySelectorAll('a')
function scrollspy() {
sections.forEach(current => {
let currentElementOffset = current.offsetTop
let scrollPosition = document.documentElement.scrollTop || document.body.scrollTop
let position = null
let currentItem = null
let currentID = null
if (current.tagName === 'H2') {
currentID = current.id
} else {
currentID = current.querySelector('h2').getAttribute('id')
}
if (currentID) {
currentItem = component.querySelector(`a[href='${document.location.pathname}#${currentID}']`)
}
if (window.innerWidth >= 768) {
position = scrollPosition + (window.innerHeight * 0.2)
} else {
position = scrollPosition + (window.innerHeight * 0.6)
}
if (currentElementOffset <= position) {
allLinks.forEach(currentLink => {
currentLink.classList.remove(activeClass)
})
if (currentItem) {
currentItem.classList.add(activeClass)
}
} else {
if (currentItem) {
currentItem.classList.remove(activeClass)
}
}
})
}
window.addEventListener('load', scrollspy())
window.addEventListener("scroll", throttle(scrollspy, 50))
})
}