Skip to content

Instantly share code, notes, and snippets.

@dinhanhthi
Created December 15, 2020 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinhanhthi/c51fa9e525253179601d2a3e1b47d0b6 to your computer and use it in GitHub Desktop.
Save dinhanhthi/c51fa9e525253179601d2a3e1b47d0b6 to your computer and use it in GitHub Desktop.
Scrolling heading inside TOC
<div class="toc">
<ol>
<li class=""><a href="#heading-1">Heading 1</a></li>
<li class=""><a href="#heading-2">Heading 2</a></li>
</ol>
</div>
// scrolling toc
// -----------------------------------------
if (document.querySelectorAll("h2, h3, h4") != null) {
function headingTOC() {
document.querySelectorAll("h2, h3, h4").forEach((heading) => {
if (document.getElementsByTagName("html")[0].scrollTop >= heading.offsetTop - 100) {
var id = heading.getAttribute("id"); // id of headings
if (id != null) {
var toc = document.getElementsByClassName("toc")[0];
if (toc != null) {
toc.querySelectorAll("a").forEach((item) => {
item.parentElement.classList.remove("toc-active");
});
document.querySelector(`.toc li a[href="#${id}"]`).parentElement.classList.add('toc-active');
}
}
}
});
}
addEventListener("scroll", headingTOC);
}
.toc-active {
& > a {
color: #fff !important;
}
&::before{
opacity: 1!important;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment