Last active
December 29, 2015 18:29
-
-
Save ryanburnette/7711090 to your computer and use it in GitHub Desktop.
Call this jQuery function on an empty div and it will populate a table of contents based on your parameters. Each toc anchor scrolls the window to that heading.
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
(function($){ | |
$.fn.sectionToc = function(params) { | |
var defaults | |
, settings | |
, headingsSelectors = [] | |
, headingsSelectorsString | |
, $headings | |
, $list = $('<ul></ul>') | |
, $toc = $(this) | |
; | |
defaults = { | |
parent: '.container:eq(0)', | |
headings: { | |
'h2': '0', | |
'h3': '1', | |
'h4': '2', | |
'h5': '3', | |
'h6': '4' | |
}, | |
animateSpeed: 50 | |
}; | |
settings = $.extend(defaults, params); | |
$toc.html(''); | |
$toc.append($list); | |
for ( var key in settings.headings ) { | |
headingsSelectors.push(key); | |
} | |
headingsSelectorsString = headingsSelectors.join(); | |
$headings = $toc.parents(parent).find(headingsSelectorsString); | |
$headings.each(function () { | |
var $thisHeading = $(this) | |
, $newItem = $('<li></li>') | |
, $newItemLink = $('<a href="#">' + $(this).html() + '</a>') | |
; | |
if ( typeof( settings.headings[String($thisHeading.prop('tagName')).toLowerCase()] ) !== 'undefined' ) { | |
$newItem.addClass('level-' + settings.headings[String($thisHeading.prop('tagName')).toLowerCase()] ); | |
} | |
$newItemLink.on('click', function () { | |
$('body,html').animate({scrollTop: $thisHeading.offset().top}, settings.animateSpeed); | |
return false; | |
}); | |
$newItem.append($newItemLink); | |
$list.append($newItem); | |
}); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment