AnchorJS Dynamic Table of Contents

An example of how to make a dynamic table of contents using AnchorJS.

by Bryan Braun

HTML

<script src="https://rawgit.com/bryanbraun/anchorjs/master/anchor.min.js"></script>
<div id="table-of-contents">
</div>

<hr />

<h2>The Phantom Menace</h2>
<p>Sed molestie augue sit amet leo consequat posuere. Vestibulum ante ipsum primis.</p>
<h2>Attack of the Clones</h2>
<p>Sed molestie augue sit amet leo consequat posuere. Vestibulum ante ipsum primis.</p>
<h2>Revenge of the Sith</h2>
<p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus.</p>
<h2>A New Hope</h2>
<p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus.</p>
<h2>The Empire Strikes Back</h2>
<p>Vivamus luctus urna sed urna ultricies ac tempor dui sagittis.</p>
<h2>Return of the Jedi</h2>
<p>Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum.</p>
<h2>The Force Awakens</h2>
<p>In condimentum facilisis porta. Sed nec diam eu diam mattis viverra.</p>

JavaScript

anchors.options.visible = 'always';
anchors.add('h2');
generateTableOfContents(anchors.elements);

// External code for generating a simple dynamic Table of Contents
function generateTableOfContents(els) {
	var anchoredElText,
  		anchoredElHref,
			ul = document.createElement('UL');

  document.getElementById('table-of-contents').appendChild(ul);

	for (var i = 0; i < els.length; i++) {
  	anchoredElText = els[i].textContent;
		anchoredElHref = els[i].querySelector('.anchorjs-link').getAttribute('href');
  	addNavItem(ul, anchoredElHref, anchoredElText);
  }
}

function addNavItem(ul, href, text) {
  var listItem = document.createElement('LI'),
		  anchorItem = document.createElement('A'),
  	  textNode = document.createTextNode(text);
  
  anchorItem.href = href;
  ul.appendChild(listItem);
  listItem.appendChild(anchorItem);
  anchorItem.appendChild(textNode);
}