Create Dynamic Table Of Contents with Javascript

Last modified: 
Thursday, April 9th, 2015
Topics: 
Javascript

Overview

This jQuery snippet will create a dynamic table of contents based on h3 tags.

It will look for a div with the class dyntoc. If found, it steps out of dyntoc, into the parent element, and scans for h3 tags. An anchor will be placed before each h3 tag contained in the parent element and a back to top link will be placed after. A dynamic table of contents will be inserted into div.dyntoc and an anchor "#dyntoc-top" will be placed above to serve as the back to top link destination. Display is adjusted with CSS as needed. Requires jQuery.

Code

// Create navigation links based h3 tags.
jQuery(document).ready(function($) {
  var links = *;
  var $toc = $('div.dyntoc').before('');
  $container = $toc.parent();  
  $('h3', $container).each(function() {
    title = $(this).html();
    name = title.toLowerCase().replace(' ', '-');
    $(this).before('

'); $(this).after(''); links += '
  • '+title+'
  • '; }); $toc.html('
      '+links+'
    '); });

    Usage

    Section 1

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

    Section 2

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

    Section 3

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.


    The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.