Last active
February 27, 2024 13:49
-
-
Save pavlo-bondarchuk/5a3ef3dd55f48de0233611b2d9fd5ab1 to your computer and use it in GitHub Desktop.
TOC Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Dakota Lee Martinez | |
* Url: https://dakotaleemartinez.com/tutorials/how-to-add-active-highlight-to-table-of-contents/ | |
* Thanks! | |
*/ | |
class Scroller { | |
static init() { | |
if (document.querySelector('.sticky-toc')) { | |
this.tocLinks = document.querySelectorAll('.sticky-toc a'); | |
this.headers = Array.from(this.tocLinks).map(link => { | |
const anchor = link.href.split('#')[1]; | |
return document.querySelector(`[id="${anchor}"]`); | |
}) | |
this.ticking = false; | |
window.addEventListener('scroll', (e) => { | |
this.onScroll() | |
}) | |
} | |
} | |
static onScroll() { | |
if (!this.ticking) { | |
requestAnimationFrame(this.update.bind(this)); | |
this.ticking = true; | |
} | |
} | |
static update() { | |
this.activeHeader ||= this.headers[0]; | |
let activeIndex = this.headers.findIndex((header) => { | |
return header.getBoundingClientRect().top > 180; | |
}); | |
if (activeIndex == -1) { | |
activeIndex = this.headers.length - 1; | |
} else if (activeIndex > 0) { | |
activeIndex--; | |
} | |
let active = this.headers[activeIndex]; | |
if (active !== this.activeHeader) { | |
this.activeHeader = active; | |
this.tocLinks.forEach(link => link.classList.remove('is-active')); | |
this.tocLinks[activeIndex].classList.add('is-active'); | |
} | |
this.ticking = false; | |
} | |
} | |
window.addEventListener('DOMContentLoaded', function (e) { | |
Scroller.init(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment