Table of contents

By Ken Hawkins

typography lists Requires EBI Visual Framework 1.1.0, 1.2.0

Programatically insert a table of contents.

Contribute a pattern

Have a great way of doing something, add it to the Style Lab. Here's how


Implementation code

Get a zip with all the sample HTML and any spaecial CSS or JS needed: Download a ZIP file More on how to use this

HTML
<section id="main-content-area">
  <div class="callout table-of-contents"></div>

  <h2>Level 2 heading</h2>
  <p>More content in a full-width container.</p>

  <h3>Level 3 heading</h3>
  <p>More content in a full-width container.</p>

  <h4>Level 4 heading</h4>
  <p>This won't be added to the table of contents.</p>
</section



JS
// Forked from https://css-tricks.com/automatic-table-of-contents/
var output = "<nav role='navigation'><h4>Table of Contents</h4><ul>";
var outputTarget = 'table-of-contents'

$("#main-content-area h2, #main-content-area h3").each(function() {
  var el = $(this),
      title = el.text();

  // don't automatically add page title and allow some tags to be ignored
  if (!(el.hasClass('page-title')) && !(el.parent().hasClass(outputTarget)) && !(el.hasClass('ignore-for-'+outputTarget))) {
    // create ids if they don't yet exist
    if (el.attr("id") == undefined) {
      el.attr("id", title.split(" ").join("-").toLowerCase());
    }

    output += "<li><a href='#" + el.attr("id") + "'>" + title + "</a></li>";
  }
});

output +="</ul></nav>";

$("."+outputTarget).prepend(output);