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();
|
}
|
});
|