reduce time complexity of toc highlighting

and solve no highlighting when heading not on sight
This commit is contained in:
Xavier Valls Pla 2020-06-25 15:34:19 +02:00
parent 136f700b91
commit f47a0f4ff6

View File

@ -1,22 +1,29 @@
function clearActiveStatesInTableOfContents() {
document.querySelectorAll('#TableOfContents ul li a').forEach((section) => {
section.classList.remove('active');
});
function elementInToC(entry) {
return document.querySelector(`#TableOfContents ul li a[href="#${entry.target.getAttribute('id')}"]`);
}
window.addEventListener('DOMContentLoaded', () => {
var previousActive = null;
const observer = new IntersectionObserver(entries => {
var currentIR = 0;
var foundActive = false;
entries.forEach(entry => {
const id = entry.target.getAttribute('id');
if (entry.intersectionRatio > currentIR) {
currentIR = entry.intersectionRatio;
clearActiveStatesInTableOfContents();
document.querySelector(`#TableOfContents ul li a[href="#${id}"]`).classList.add('active');
if (!foundActive && entry.isIntersecting) {
if(previousActive) {
previousActive.classList.remove('active');
}
});
elementInToC(entry).classList.add('active');
foundActive = true;
previousActive = elementInToC(entry);
}
else {
elementInToC(entry).classList.remove('active');
}
})
if (!foundActive) {
previousActive.classList.add('active');
};
});
// Track all headers that have an `id` applied