Jake Vanderwerf
2026-05-11 ac444cba221832c012c0435fdc8339fe9f37febb
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
class OnThisPage {
    constructor() {
        this.initElements();
        this.initListeners();
    }
 
    initElements() {
        this.selectors = {
            nav: 'nav.on-this-page',
            toggle: 'button.toggle',
            icon: 'button.toggle .icon'
        }
        this.ui = window.uiFromSelectors(this.selectors);
 
        let items = this.ui.nav.querySelectorAll('li a');
        this.ui.items = {};
        this.ui.sections = {};
        this.selectors.items = [];
 
        for (let item of items) {
            let id = item.getAttribute('href');
            this.ui.items[id.replace('#', '')] = item.closest('li');
            this.selectors.items.push(id);
            this.ui.sections[id.replace('#', '')] = document.querySelector(id);
        }
        this.selectors.items = this.selectors.items.join(',');
    }
 
    initListeners() {
        this.ui.toggle.addEventListener('click', () => {
            let icon = this.ui.nav.classList().contains('open') ? 'icon-x-square' : 'icon-plus-square';
            console.log('Changing icon to: '+icon);
            this.ui.icon.className = 'icon '+icon;
        });
 
        this.observer = new IntersectionObserver(
            (entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
 
                        let index = Object.keys(this.ui.items).indexOf(entry.target.id);
                        let i = 0;
                        for (let  item of Object.values(this.ui.items)) {
                            item.classList.toggle('active', index === i);
                            // item.classList.toggle('adj', i === index +1 || i === index -1);
                            i++;
                        }
                    }
                });
            },
            {
                rootMargin: '-50% 0px -50% 0px',
                threshold: 0
            }
        );
 
        for (let section of Object.values(this.ui.sections)) {
            console.log('Observing section: ', section);
            this.observer.observe(section);
        }
    }
}
 
// Initialize
document.addEventListener('DOMContentLoaded', () => {
    if (document.querySelector('nav.on-this-page')) {
        window.onThisPage = new OnThisPage();
    }
});