When you have a large HTML document is often a tedious task to create a table of contents for all the sections of your page. Fortunately, jQuery offers a simple and practical solution to this problem.
We only need to know what are the main headings that mark up the beginning of each section or block. Done that, we can write the following plugin:
(function($) {
$.fn.autoToc = function(options) {
var settings = {
titles: 'h2',
section: 'section',
text: 'Table of contents'
};
options = $.extend(settings, options);
return this.each(function() {
var element = $(this);
var html = '<div id="toc"><h3>' + options.text + '</h3><ul>';
$(options.titles, element).each(function(i) {
var title = $(this);
title.attr('id', options.section + '-' + (i + 1));
html += '<li><a href="#' + options.section + '-' + (i + 1) + '">' + title.text() + '</a></li>';
});
html += '</ul></div>';
$(html).insertBefore($(options.titles + ':first', element));
});
};
})(jQuery);
Our plugin accepts three options:
titles
– the heading tag that marks up the beginning of each sectionsection
– the start string to build up the ID for each headingtext
– the title of the table of contents (defaults to "Table of contents").
An example:
$(function() {
$('body').autoToc();
});
[view-example url="http://jsfiddle.net/gabrieleromanato/CSqDt/"]