Created
December 15, 2020 22:40
-
-
Save dinhanhthi/c51fa9e525253179601d2a3e1b47d0b6 to your computer and use it in GitHub Desktop.
Scrolling heading inside TOC
This file contains 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
<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> |
This file contains 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
// 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); | |
} |
This file contains 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
.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