Skip to content

Instantly share code, notes, and snippets.

@softplus
Created April 25, 2021 17:06
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 softplus/0dd35b72874e81728bd1a28b1dd0fd64 to your computer and use it in GitHub Desktop.
Save softplus/0dd35b72874e81728bd1a28b1dd0fd64 to your computer and use it in GitHub Desktop.
Dynamic table of contents, using jQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.js" integrity="sha512-HNbo1d4BaJjXh+/e6q4enTyezg5wiXvY3p/9Vzb20NIvkJghZxhzaXeffbdJuuZSxFhJP87ORPadwmU9aN3wSA==" crossorigin="anonymous"></script>
<script>
(function() {
var $toc = $('#TableOfContents');
if ($toc.length > 0) {
var $window = $(window);
function onScroll(){
var currentScroll = $window.scrollTop();
var h = $('.article-entry h1, .article-entry h2, .article-entry h3, .article-entry h4, .article-entry h5, .article-entry h6');
var id = "";
h.each(function (i, e) {
e = $(e);
if (e.offset().top - 10 <= currentScroll) {
id = e.attr('id');
}
});
var active = $toc.find('a.active');
if (active.length == 1 && active.eq(0).attr('href') == '#' + id) return true;
active.each(function (i, e) {
$(e).removeClass('active').siblings('ul').hide();
});
$toc.find('a[href="#' + id + '"]').parentsUntil('#TableOfContents').each(function (i, e) {
$(e).children('a').addClass('active').siblings('ul').show();
});
}
$window.on('scroll', onScroll);
$(document).ready(function() {
$toc.find('a').parent('li').find('ul').hide();
onScroll();
document.getElementsByClassName('article-toc')[0].style.display = '';
});
}
})();
</script>
@softplus
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment