Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Last active December 12, 2015 12:09
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 luckyshot/4770316 to your computer and use it in GitHub Desktop.
Save luckyshot/4770316 to your computer and use it in GitHub Desktop.
Create table of contents from headings (jQuery)
#toc li {
font-size: 80%;
line-height: 1;
}
#toc .h2 {
font-size: 90%;
}
#toc .h3 {
font-size: 70%;
margin-left: 1em;
opacity: 0.8;
}
#toc .h4 {
font-size: 60%;
margin-left: 2em;
opacity: 0.6;
}
#toc a {
text-decoration: none;
}
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
// Create table of contents for posts
// Gets content from #post-content and fills the list in #toc
var toc = function( headers, toc )
{
$( headers ).each(function(index) {
// replaces tags, replaces non alphanumeric, replaces spaces with dashes
var anchor = $(this).html()
.replace(/(<([^>]+)>)/ig,"")
.replace(/([^a-zA-Z0-9 ]+)/g, '')
.replace(/\s+/g, '-')
.toLowerCase();
$(this).attr('id', anchor);
if ( $(this).prop("tagName") == 'H2' )
{
$( toc ).append('<li class="h2"><a href="#' + anchor + '">' + $(this).html() + '</a></li>');
}
else if ( $(this).prop("tagName") == 'H3' )
{
$( toc ).append('<li class="h3"><a href="#' + anchor + '">' + $(this).html() + '</a></li>');
}
else
{
$( toc ).append('<li class="h4"><a href="#' + anchor + '">' + $(this).html() + '</a></li>');
}
});
};
toc( "#wrap>h2,#wrap>h3,#wrap>h4", '#toc' );
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment