Skip to content

Instantly share code, notes, and snippets.

@ls-lukebowerman
Created January 26, 2013 05:33
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 ls-lukebowerman/4640391 to your computer and use it in GitHub Desktop.
Save ls-lukebowerman/4640391 to your computer and use it in GitHub Desktop.
Simple jQuery table of contents generator. Scans page for <h2> headings, adds IDs to those headings that don't have any and then prepends a Table of contents to the page.
// Assumes availability of jQuery...
function generate_toc() {
// Get the headings
var body = $('body');
var headings = body.find('h2');
// We don't need a table of contents if we don't have any headings
if (headings.length == 0) return false;
// Setup the div#toc
var toc = $('<div class="toc"><ul></ul></div>');
// Setup the div#toc h3 & div#toc ul
headings.each(function(heading) {
// Get the existing heading id or setup a new one based on the heading text
var title = heading.text();
// If the heading doesn't have an id attribute we need to make one up
if(!heading.attr("id")) {
// We'll lowercase the heading text, remove any white space and make that the id
heading.attr('id',title.toLowerCase().replace(/\W/g,''));
}
// Add a li element with anchor link to the heading
toc.find('ul').append('<a href="#'+heading.attr('id')+'>'+content+'</a>');
});
// Add our link to the top anchor
toc.find('ul').append('<a href="#top">Top</a>');
// Prepend our TOC to the document
body.prepend(toc);
// Put a top anchor at the very beginning of the document
body.prepend('<a id="#top"></a>');
// Check if there's already a anchor hash - scroll there if needed
// This will make sure that bookmarks with anchors will behave as expected
if(window.location.hash.length > 0) {
$('html, body').animate({
scrollTop: $(window.location.hash).offset();
}, 2000);
}
}
$(document).ready(function(){
generate_toc();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment