Created
December 6, 2012 00:26
-
-
Save sbp/4220844 to your computer and use it in GitHub Desktop.
Table of Contents generation in JavaScript using jQuery
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
function contents() { | |
var first = $('h2:first'); | |
if (!first) return; | |
var p = '<p><strong>Contents</strong>'; | |
var ol = '<ol id="contents"></ol>'; | |
first.before('<div class="contents">' + p + ol + '</div>'); | |
var outer = $('#contents'); | |
$('h2, h3, h4').map(function (i) { | |
var header = $(this); | |
header.attr('id', 'tmp.' + (i + 1)); | |
var link = '<a href="#tmp.' + (i + 1) + '">' + header.text() + '</a>'; | |
var item = '<li class="' + this.tagName + '">' + link; | |
if (typeof previous == 'undefined') { | |
outer.append(item) | |
} else if (this.tagName > previous) { | |
$('li:last', outer).append('<ul>' + item + '</ul>') | |
} else if (this.tagName < previous) { | |
$('ul:last', outer).parent().after(item) | |
} else { $('li:last', outer).after(item) } | |
previous = this.tagName; | |
}); | |
} | |
$(document).ready(contents); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment