-
-
Save softplus/0dd35b72874e81728bd1a28b1dd0fd64 to your computer and use it in GitHub Desktop.
Dynamic table of contents, using jQuery
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
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Documented at https://johnmu.com/dynamic-toc-io/