Skip to content

Instantly share code, notes, and snippets.

@adbertram
Created February 25, 2020 22:23
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 adbertram/0e10f5dbac3fe478afb3038a416d6d84 to your computer and use it in GitHub Desktop.
Save adbertram/0e10f5dbac3fe478afb3038a416d6d84 to your computer and use it in GitHub Desktop.
<script>
var contentsTitle = "Table of Contents"; // Set your title here, to avoid making a heading for it later
var ToC = "<h2>"+contentsTitle+"</h2>";
ToC += "<nav role='navigation' class='table-of-contents'><ul>";
var first = false;
$("h2,h3").each(function() {
var el = $(this);
if (first === false) {
first = true;
$('<span id="dynamictoc"></span>').insertBefore(el);
}
var title = el.text();
if (title.indexOf(";") >= 0) {
var title = title.split(";")[1];
}
if (title) {
var link = "#" + el.attr("id");
if (el.is("h2")) {
ToC += "<li><a href='" + link + "'>" + title + "</a></li>";
} else if (el.is("h3")) {
ToC += "<li style='margin-left:2em'><a href='" + link + "'>" + title + "</a></li>";
}
}
});
ToC += "</ul></nav>";
console.log(ToC);
$("#dynamictoc").html(ToC);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment