Created
January 26, 2013 05:33
-
-
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.
This file contains hidden or 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
// 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