Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
48 lines (43 loc) · 1.82 KB
/
Copy pathscript.js
File metadata and controls
48 lines (43 loc) · 1.82 KB
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
const navigation = document.querySelector('.topnav');
const toggle = document.querySelector('.nav-toggle');
const links = [...document.querySelectorAll('.navlinks a')];
const mobile = window.matchMedia('(max-width: 960px)');
function closeNavigation() {
navigation.classList.remove('is-open');
toggle.setAttribute('aria-expanded', 'false');
}
navigation.classList.add('is-enhanced');
toggle.hidden = false;
toggle.addEventListener('click', () => {
const open = navigation.classList.toggle('is-open');
toggle.setAttribute('aria-expanded', String(open));
});
links.forEach(link => link.addEventListener('click', closeNavigation));
navigation.querySelector('.brand').addEventListener('click', closeNavigation);
document.addEventListener('keydown', event => {
if (event.key === 'Escape' && navigation.classList.contains('is-open')) {
closeNavigation();
toggle.focus();
}
});
document.addEventListener('click', event => {
if (!navigation.contains(event.target)) closeNavigation();
});
mobile.addEventListener('change', closeNavigation);
// Keep the section indicator in sync with reading position, including deep links.
if ('IntersectionObserver' in window) {
const visibleSections = new Map();
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => visibleSections.set(entry.target.id, entry.isIntersecting));
const current = [...document.querySelectorAll('main section[id]')]
.find(section => visibleSections.get(section.id));
links.forEach(link => {
if (current && link.hash === `#${current.id}`) {
link.setAttribute('aria-current', 'location');
} else {
link.removeAttribute('aria-current');
}
});
}, { rootMargin: '-15% 0px -50% 0px', threshold: 0 });
document.querySelectorAll('main section[id]').forEach(section => observer.observe(section));
}