Table of Contents generator for anchors with MooTools

Posted on May 3, 2008 in MooTools |

For those pages with loads of text a table of contents would be nice, with anchors located in relevant sections. Thing is that going through a page with thousands of words and headings is no fun at all.

I made a script using the lovely MooTools that gets all the elements with a given CSS selector (using the Elements.Selectors syntax) and then builds an unordered list of links, with the element text as the title, and an anchor placed in that element.

What this script does is append an anchor above each element that matches the given CSS selector, and then builds an unordered based on the links previously inserted. It then injects the list into a given element. There are also options that allow a ‘back to top’ link dynamically inserted at each anchor.


To add the list and anchors simply instantiate an object of that class, and then call the output method with the destination for the list of links. It’s as simple as this:

var toc = new tableOfContents('h2', 'tocList');
toc.output('toc', {returnLink:true, returnLinkText:'top', inject:'after'});


returnLink – boolean, decides whether to add a “back to top” link at each anchored element. Defaults to false.
returnLinkText – text to use when adding “back to top” link. Defaults to “back to top”.
inject – String to decide where to insert the “back to top” link relative to anchored elements. Values are : before, after, top. Defaults to inside.


MooTools v1.1 – Compile with Element.Selector

Example and Documentation

A full working example with source code is found here. View the source for code and documentation.

Tested Browsers

  • IE 6/7
  • Safari 3.1 (PC Version)
  • Opera 9.1
  • Firefox 2+