Created
August 7, 2012 05:45
-
-
Save ls-lukebowerman/3282059 to your computer and use it in GitHub Desktop.
Table of Contents generator
This file contains 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
$(document).ready(function() { | |
// Only find headings within the article ID to save overhead | |
// (we don't care about headings outside of the article for the TOC | |
$('#article').each(function() { | |
var article = $(this); | |
var toc = $('<div class="toc"><h3>Table of Contents</h3><ul></ul></div>'); | |
var toc_ul = toc.find('ul'); | |
article.find('h2').each(function() { | |
// Add a ID (anchor) to each heading | |
// A little ugly since it clobbers existing IDs | |
$(this).attr('id',$(this).html().replace(/ /gi,'-').toLowerCase()); | |
// Add item to table of contents | |
toc_ul.append('<li><a href="#'+$(this).attr('id')+'">'+$(this).html()+'</a></li>'); | |
}); | |
article.prepend(toc); | |
// @TODO - would be nice to detect anchors and scroll user to correct location if they're following a link or bookmark (since the heading IDs won't be in place until after page load | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Table of Contents