Update 23-Mar-2010: Code updated to allow multiple TOCs per page, if desired. More information available in the release notes.

A jQuery plugin that creates a table of contents for all header elements within the parent DOM element provided. (Based on original by Dimitri Spassov.)

By default, jqTOC produces a fixed, floating div box with the title “Content”, in the top right of the browser window. When the box is clicked a new div will display a list of all H1, H2, H3 elements within scope of the parameter element. Each TOC element is a clickable link to the title in the document.

Start and end heading levels can be specified. All heading levels 1, 2, 3, is the default.


Call Sample

Basic call, using defaults, will show all level 1,2,3 headings within an element with ID of “content”. In the example below jqTOC is called from within .ready() to ensure that the DOM has fully loaded – you can also call jqTOC from your own functions.

$(document).ready(function(){
$('#content').jqTOC();
});

Parameters

Default Parameters

tocWidth: 220,
tocTitle: 'Content',
tocStart: 1,
tocEnd : 3,
tocContainer : 'toc_container',
tocAutoClose : true
tocShowOnClick : true,
tocTopLink : 'top'

Override Default Parameters

Override the default(s) as below. Parameters can be in any order.

$(document).ready(function(){
$('#content').toc({
tocWidth:500,
tocTitle: "Table of Contents",
tocStart: 2,
tocEnd: 10,
tocAutoClose: false
});
});

Fixed Positioning

Fixed positioning in IE7 and Firefox works. In IE5/6 it doesn’t. The jqTOC solution implements some patches to permit fixed positioning in IE5/6. If you don’t care for fixed positioning, or you don’t need to support IE5/6, then you can remove the following code – these do not pass strict validation.

CSS Cludges

With the styling that follows everything works, except you now have two scrollbars. This css hides the original browser scrollbar. The first “*” is ignored by all non-IE5/6 browsers, as invalid.

* html {overflow-x:auto; overflow-y:hidden;}

Need to tell IE5/6 to position absolute, as that and relative is all it understands. Also, IE will float the TOC div over the vertical scrollbar, which looks tacky. The margin-right is not necessary for fixed positioning, but shifts the TOC to prevent the TOC overlapping the scrollbar.

* html #toc_container {position:absolute; margin-right:15px;}

The main part of the cludge. The padding is not required, but makes things look better after the zero margin is applied.

body {
margin:0;
padding:0 10px 0 10px;
height:100%;
overflow-y:auto;
}

Stricter Validation

You can replace the “* html” line in the CSS with this code in the header of your HTML file for stricter validation. Since we already use the ‘star’ technique anyway, it’s probably not worth using this stricter version.

Known Issues