Skip to content

Instantly share code, notes, and snippets.

@badabingbreda
Created May 25, 2018 22:40
Show Gist options
  • Save badabingbreda/54ad9a31f7af25bca162c9b50dcd5400 to your computer and use it in GitHub Desktop.
Save badabingbreda/54ad9a31f7af25bca162c9b50dcd5400 to your computer and use it in GitHub Desktop.
Auto TOC - create TOC from H4-H5 hierarchy
(function($) {
$(document).ready(function(){
var $toc = $('#toc'), // toc id
appendthis = ''; // build the toc
$toc.html(''); // clear receiving <div id="toc"></div>
//opening tag
appendthis +=('<ul>');
var previous = 'H4';
// just assume we start of with a H4
$('h4,h5').each( function( index ) {
$(this).prepend('<a id="index_' + index +'"/>');
if ( previous !== $(this).prop('tagName') ) {
if (previous == 'H4' ) appendthis+=('<ul>');
if (previous == 'H5' ) appendthis+=('</ul>');
}
appendthis+=('<li><a href="#index_'+index+'" class="fl-scroll-link">'+ $(this).text() +'</a></li>');
// set this as previous tagname
previous = $(this).prop('tagName');
});
// is last element h5? We need an extra ul because we're ending with h5
if (previous == 'H5' ) appendthis+=('</ul>');
// close it up
appendthis+=('</ul>');
$toc.append( appendthis );
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment