Automatic jQuery Table of Contents Generation

Showing 1-1 of 1 messages
Automatic jQuery Table of Contents Generation
Sean B. Palmer
04/04/10 06:31
This script will do three things:

* Add IDs to all h2, h3, and h4 headers.
* Create a list above the first h2.
* Populate the list with structured links to the headers.

If there is no h2, the script won't do anything.

function contents() {
   var first = $('h2:first')
   if (!first) return
   first.before('<ul id="contents"></ul>')
   var outer = $('ul#contents')

   $('h2, h3, h4').map(function (i) {
      var header = $(this)
      header.attr('id', 'tmp.' + (i + 1))

      var link = '<a href="#tmp.' + (i + 1) + '">' + header.text() + '</a>'
      var item = '<li class="' + this.tagName + '">' + link
      if (typeof previous == 'undefined')
         outer.append(item)
      else if (this.tagName > previous)
         $('li:last', outer).append('<ul>' + item + '</ul>')
      else if (this.tagName < previous)
         $('ul:last', outer).parent().after(item)
      else $('li:last', outer).after(item)
      previous = this.tagName
   })
}

Example of use:

<!DOCTYPE html>
<title>Table of Contents Generation</title>
<script src="jquery.js"></script>
<script>
function contents() { ... }
$(document).ready(contents)
</script>

<h1>Table of Contents Generation</h1>
<h2>An Example</h2>
<h3>Subheading</h3>

The #tmp.1 nature of the links is to indicate that they're
automatically generated based on position in the document and not to
be relied upon, but of course it's easy to modify the IDs if you like.