Create a Dynamic Table of Contents (TOC)

JavaScript/jQuery Generated TOC

Purpose

For long pages with a lot of content, it may be desirable to have a TOC somewhere on your page. It is far easier to have the TOC dynamically built when the page is loaded by the browser, and the code to do that is suprisingly simple.

JavaScript Code

This code will scan through header tags <h1> through <h3> (you can change that on line 6) and will generate a list of links from them.

<script type="text/javascript">
$(document).ready(function() {
		var toc = '';
		var cntr = 0;
		var tocId;
		function getId(headerText) {
			var idStyle = 'naturalText';
			if (idStyle === 'naturalText') {
				//Change spaces to dashes, and make all lower-case. Limit to six words.
				headerText = headerText.toLocaleLowerCase();
				hdrText = headerText.split(' ', 6);
				return hdrText.join('-');
			} else {
				//the id's should be "toc1", "toc2", "toc3", etc.
				return 'toc' + ++cntr;
			}
		}
		$('h1, h2').each(function(e) {
			$hdr = $(this);
			if (!(tocId = $hdr.attr('id'))) { //hdr does not already have an id
				tocId = getId($hdr.text());
				$hdr.attr('id', tocId);
			}
			toc += '<li class="' + $hdr[0].tagName + '"><a href="#' + tocId + '">' + $hdr.text() + '</a></li>';
		});
		$('#toc').html('<ul>' + toc + '</ul>');
	});
</script>

Example

The following block was dynamically created when this page loaded into your browser.

Table of Contents

In this example, I created an empty <nav> block in the page where the TOC should appear.

<nav id="toc"></nav>

Then, so the list of links doesn’t look quite so ugly, I applied this CSS:

nav ul {
	list-style-type: none;
	margin-left:0;
	padding-left:0;
}
nav li.H1 {
	padding-left:0em;
}
nav li.H2 {
	padding-left:2em;
	font-weight:bold;
}
nav li.H3 {
	padding-left:4em;
}
nav a {
	text-decoration:none;
	color:black;
}