Welcome, visitor! RegisterLogin

Table of Contents JS Widget with Smooth Scroll

A few years ago I build a small Javascript widget which would automatically build a table of contents out of the article on the page. All you need in the HTML is a location to store the pulled headings, in this example I’ve used an empty div with the class of ‘toc’.
 <div class=""></div> 
Add the below to your JS file. This will generate a list of items based on headings and add them to the above element. Smooth scrolling has been tweaked from the example on CSS Tricks.
// Build a table of contents
$(function() {
  // assuming the main content is within the </article> tag they can all be picked up by using the header selector in jQuery
  $("article :header").each(function() {
    // Assign the text of the heading to a variable so we can add this to a list later
    var title = $(this).text();
    // Each heading is assigned a unique ID we can use to target it. This will be added to the list so we can anchor to the correct heading.
    var link = "#" + $(this).attr("id");
    // We will then need to build the link to add into the table of contents. This adds the link and title as defined above.
    var toc = "<a href='" + link + "'>" + title + "</a><br />";
    // toc will be appended to the empty div creating our list of headings.

// Smooth scrolling for jQuery, taken from CSS Tricks post
// https://css-tricks.com/snippets/jquery/smooth-scrolling/
$(function() {
  // Smooth scroll the page when clicking one of the contents links.
  $("a[href*=\\#]:not([href=\\#])").click(function() {
    if (
      location.pathname.replace(/^\//, "") ==
        this.pathname.replace(/^\//, "") &&
      location.hostname == this.hostname
    ) {
      var target = $(this.hash);
      target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
      if (target.length) {
            scrollTop: target.offset().top
        return false;
The smooth scroll was tweaked from the snippet on CSS Tricks.