Skip to content

Instantly share code, notes, and snippets.

@sojournercntl
Created May 1, 2020 23:05
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 sojournercntl/1c5813ceab7779d2dbc0afb3279f818b to your computer and use it in GitHub Desktop.
Save sojournercntl/1c5813ceab7779d2dbc0afb3279f818b to your computer and use it in GitHub Desktop.
TOC JS
jQuery.tableOfContents =
function (tocList) {
jQuery(tocList).empty();
var prevH2Item = null;
var prevH2List = null;
var index = 0;
// foreach
jQuery("h1, h2, h3, h4, h5, h6").each(function() {
// var anchor = "<a name='" + index + "'></a>";
// jQuery(this).before(anchor);
var li = "<li><a href='#" + jQuery(this).attr('id') + "'>" + jQuery(this).text() + "</a></li>";
if( jQuery(this).is("h2") ){
prevH2List = jQuery('<ul class="doc-nav"></ul>');
prevH2Item = jQuery(li);
prevH2Item.append(prevH2List);
prevH2Item.appendTo(tocList);
} else if ( jQuery(this).is("h1") ){
if(prevH2List !== null) {
prevH2List.before('<h5>'+jQuery(this).text()+'</h5>');
} else {
$(tocList).append('<h5>'+jQuery(this).text()+'</h5');
}
} else {
prevH2List.append(li);
}
index++;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment