FF IE9+ Chrome

Automatic Anchor Links from Headers

Author: Jon Muller

Description: This jQuery script automatically generates a table of contents from all of the headers on the page (H1, H2, CUSTOM etc), enabling viewers to navigate to key sections of with ease. An HTML anchor is dynamically inserted into each header, making it navigable. The script supports the following customizations:

  • Specify the header elements the script should parse to create the TOC (defaults to "H1", "H2", "H3", and ".customheader" class).
  • Define whether to animate the scroll to header mechanic.
  • Define the maximum number of characters the script should extract from each header to create each TOC link.
  • Create and position an empty DIV container anywhere on the page to display the TOC.

The TOC container can be made "sticky" with additional changes, so it always appear in view. See the section "Making the Table of Contents Sticky" by the author below.

See also: jQuery Scroll to Top Control and Scrolling HTML Bookmarks


Installation Directions

Insert the following script in the HEAD section of your page:

Select All

And download the following .js file: jqueryheaderanchors.js

Then, define an empty DIV to house the generated Table of Contents. By default the DIV should have an ID of "tocbox":

<div id="tocbox"></div>

Inside the jqueryheaderanchors.js, you can modify various settings of the script:

var targetels= ['h1', 'h2', 'h3', '.customheader']
var outputdivid = 'tocbox' // id of empty element to house TOC links
var headerlength = 70 // max length of each header link
var trailingmark = '...' // trailing text to add to each of header link if necessary
var animated = true // animate scrolling?
var uloutput = '<ul class="tableofcontents">\n' // UL and classname to use for the generated TOC container

Making the Table of Contents Sticky (Author Notes)

The generated Table of Contents can be made sticky in a variety of ways:

On my own site, you can see this in action- look at the right hand column of my kneeling chairs page. Scroll the page and notice how the TOC stays visible. The site is Wordpress based, so I'm using this script (a slight variation) in addition to the Q2W3 widget to make the TOC container sticky.