Create Table Of Contents (TOC) With Multi-level List In JavaScript


Ever wondered to generate a dynamic Table of Contents list in pure JavaScript without using a single line of jQuery? We have successfully programmed a robust TOC Script in JavaScript and CSS3 entitled as "TOC Plugin V 2.0". This plugin will create a multi-level Table of Contents from a webpage's heading tags on page load in a fraction of a second!

TOC Plugin - Table of contents build in JavaScript

DEMO: The list bellow is dynamically created on page load using this TOC Script.

Introduction To TOC Plugin V 2.0

TOC Plugin V 2.0 is the upgraded version of the TOC Script we released last week. It is much more dynamic in its  functionalities and features compared to the previous one. It is a unique script that auto-generates a TOC from the heading tags (i.e. H1, H2, H3, H4, H5, H6) of the page and adds anchor links to each nested list item.

I recommend the previous version for those bloggers who do not write in-depth content with heading tags of the lower level i.e. (h3,h4,h5). But if you do use multi-level subheadings in your content then V2.0 best suits you.  This new version supports both a flat list or multi-level list of heading tags.

Why Use a TOC?

For webmasters and bloggers who write lengthy articles and divide the article in several sub-sections, the readers may find it difficult reading such long posts without a friendly navigation. The only solution to better present long, lengthy articles is displaying a "Table Of Contents."

TOC is one such feature that you often see on Wikipedia pages to provide easy navigation for long Articles. Wikipedia loves adding a TOC because it helps the readers to jump from one section to another easily.

Is TOC Plugin SEO Friendly?

A TOC gives a basic summary to search engines of what your article is all about. The anchor links inside a TOC offers an added benefit to your SEO efforts. Google loves anchor links and especially when these links are meaningful and provide better navigation and understanding of your blog content.

The contents list generated using TOC plugin is SEO friendly. Anchor links inside it are easily crawled and indexed by search robots. See the image below taken from our last blog post:

JavaScript "Table of Contents" is SEO friendly

Update: TOC V2.0 Anchor links are instantly indexed and crawled by Google minutes after we published this post! :)

Table of contents anchor links indexed by Google

TOC Plugin is must to have if you are serious about ranking high in SERPs.

Features of TOC Plugin

This new version has some additional features as listed below:

  • Coded in pure JavaScript
  • Supports Nested heading tags
  • Numbered Navigation With Counters
  • Finds Heading tags from H2-H6 automatically
  • Adds unique ID to each content section automatically
  • Adds unique ID to each list of anchor links inside TOC 
  • Supports both Flat list & Multilevel List
  • Show/Hide Option
  • Compressed Script
  • Lightweight and fast.
  • SEO Friendly
  • Easily Customized
  • Mobile responsive
  • Executes only when invoked!

How Does It Work?

Optional: You may skip this section if you are not interested in understanding the programming logic used to build this plugin. Click here to go straight to the installation guide.

I have shared the compressed script in the installation section for performance purpose but to give you a more clear idea of how the script gets the list of heading tags and how it converts them into anchor links, please read the detailed explanation below.

Methods Used

The backbone of this entire script is based on using a string search() method with RegExp.

I started by using the getElementById() method to search for all heading tags located inside the DOM having ID "post-toc".

To search for the heading tags <h2>, <h3>, <h3> etc.  I coined a search pattern as explained below.

Using JavaScript Regular Expressions

A regular expression, as you may know is a sequence of characters that forms a search pattern. To search for heading tags, we will need to first create a RegExp or search pattern.

In HTML a heading title will have the following structure:

<h2>Your Sub Heading Text</h2>

Where <h2> is the opening tag and </h2> is the closing tag. This headline tag could also contain attributes or nested tags such as:

<h2 id="xyz">Your Sub Heading Text With a <a href="#">Hyperlink</a></h2>  

In order to perform a perfect search I came up with the following search pattern after many trials and errors.

/<h([\d]).*?>(.*?)<\/h([\d]).*?>/gi

The pattern above is divided into three important groups as discussed below:

1st Group: ([\d])

  • \d matches a digit (equal to [0-9]) (Matches the opening tag)

2nd Group: (.*?)

  • .*? matches any character between opening and closing tags.

3rd Group: ([\d])

  • \d matches again a digit or single character (equal to [0-9]) (Matches the closing tag)

Other matches

  • <h matches the characters <h literally (case insensitive)
  • .*? matches any character (except for line terminators)
  • > matches the character > literally (case insensitive)
  • < matches the character < literally
  • \/ matches the character / literally
  • h matches the character h literally

Global pattern flags

  • g modifier: global. All matches (don't return after first match)
  • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

This expression is then passed to replace() function as a search argument.

Using String replace() Method

Once a match is found, the replace method passes these three groups as values to a function with four parameters.

.replace(/<h([\d]).*?>(.*?)<\/h([\d]).*?>/gi,function(Newheading,opening,Title,closing)

I hope the colors may better help you in understanding how the RegExp groups refer to which parameter.

The function takes these values and performs these tasks:

  • It first checks if opening tag is equal to closing tag. If it is the function will continue running else it will exit.
  • It will compare the opening tag integer value against the item level.
  • The TOC displays the list in multi-levels where each level represents the hierarchy.  For example H2 is set to be at level 1, H3 at level 2, H4 at level 3, and so on.
  • If opening tag is greater than the level, then start the array list by appending <ol>  at its beginning.
  • Else If opening tag is less than the level, then close the array list by appending </ol></li> at its end.
  • Assign a unique ID to each Heading and return it back as Newheading.
  • The replace() method then replaces the old heading on page with Newheading containing the unique ID.
  • The array lists are added inside the variable mbtTOC which is then appended inside the DOM mbtTOC2 using innerHTML()
  • The function is invoked only when mbtTOC2() is called.

Programming The CSS Counters

The final part was styling the numbered list, assigning a unique index number to each list item. The default look of the TOC ordered list without CSS styling looks like this:

table of contents with multi levels

Which of course does not build a nested relationship between the link at all and is not a good UI.

However after assigning different CSS classes to each ordered list, I was able to transform the look of TOC to something more user friendly:

.point2 {list-style-type:lower-alpha} 
.point3 {list-style-type:lower-roman} 
.point4 {list-style-type:disc}

table of contents with multiple levels

The alpha-numeric and Roman values does help in better understanding the relationship between parent and child items. But what if you want only numbers? Something exactly similar to wikipedia TOC? For that CSS counters came in handy!

I came across CSS counters few years back when I introduced a numbered threaded comments system for blogger blogs.

Nested Numbering Of List Items

CSS counters are simple "variables" maintained by CSS whose values can be incremented by CSS rules.

For CSS counters the following properties are used:

  • counter-reset - Creates or resets a counter
  • counter-increment - Increments a counter value
  • content - Inserts generated content
  • counter()function - Adds the value of a counter to an element

Using all these available properties I crafted the following styles:

.mbtTOC2 ol{counter-reset:section1;list-style:none}
.mbtTOC2 ol ol{counter-reset:section2}
.mbtTOC2 ol ol ol{counter-reset:section3}
.mbtTOC2 ol ol ol ol{counter-reset:section4}
.mbtTOC2 ol ol ol ol ol{counter-reset:section5}
.mbtTOC2 li:before{content:counter(section1);counter-increment:section1;position:relative;padding:0 8px 0 0;font-size:18px}
.mbtTOC2 li li:before{content:counter(section1) "." counter(section2);counter-increment:section2;font-size:14px}
.mbtTOC2 li li li:before{content:counter(section1) "."counter(section2) "." counter(section3);counter-increment:section3}
.mbtTOC2 li li li li:before{content:counter(section1) "."counter(section2) "."counter(section3) "." counter(section4);counter-increment:section4}
.mbtTOC2 li li li li li:before{content:counter(section1) "."counter(section2) "."counter(section3) "." counter(section4)"." counter(section5);counter-increment:section5}

Where section1, section2, section3 etc. represents CSS counters for the different list levels. In other words they represent the heading tags from H2-H5. I concatenated a counter with its sub-counter in order to create the nested numbered list appearance. (i.e. 1 > 1.1, 1.2 > 1.2.1 and 1.2.1 > 1.2.1.1)

The result was a beautiful interface with nested numbered list as shown below:

table of contents with nested numbered list

Showing and Hiding The ToC

In version two, I replaced the FontAwesome toggle Icon with a Show/Hide toggle link. The function mbtToggle2() first checks the current TOC state, and then generates a new text and a new display style based on that information.

Show/hide button in "Table of contents"

It is called whenever the user clicks on the Show or Hide link, thus making it easy to toggle the content.

Installation Guide

TOC Plugin can easily be installed on any platform. Whether it is a wordpress site, blogspot blog or a simple HTML page. The installation guide consists of three main steps:

  1. Add the JS script and CSS code above </head> tag
  2. Enclose the content section with ID "post-toc"
  3. Add the container Div and the calling function to the page where you wish to display the TOC.

For simplicity, I will discuss the installation steps for blogger blogs only. You can get an idea from these steps in order to integrate the plugin on your 3rd-party CMS platforms.

Add a 'Table Of Contents' In Blogger Posts & Pages

Most blogspot users refer to this plugin as a Table Of Contents widget while in fact it is just a script that needs to be added inside the template and post editor. So using the word widget would be incorrect here, so lets just call it a TOC plugin in short.

Follow these easy steps:

  1. Sign in Blogger > Template
  2. Backup your template
  3. Click "Edit HTML"
  4. Just above </head> tag paste the following source links:
    <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'/>
    <script type='text/javascript'> 
    //<![CDATA[ 
    //*************TOC Plugin V2.0 by MyBloggerTricks.com 
    function mbtTOC2(){var a=1,b=0,c="";document.getElementById("post-toc").innerHTML=document.getElementById("post-toc").innerHTML.replace(/<h([\d]).*?>(.*?)<\/h([\d]).*?>/gi,function(d,e,f,g){return e!=g?d:(e>a?c+=new Array(e-a+1).join("<ol class='point"+a+"'>"):e<a&&(c+=new Array(a-e+1).join("</ol></li>")),b+=1,c+='<li><a href="#point'+b+'">'+f+"</a>",a=parseInt(e),"<h"+e+" id='point"+b+"'>"+f+"</h"+g+">")}),a&&(c+=new Array(a+1).join("</ol>")),document.getElementById("mbtTOC2").innerHTML+=c}function mbtToggle2(){var a=document.getElementById("mbtTOC2"),b=document.getElementById("Tog");"none"===a.style.display?(a.style.display="block",b.innerHTML="hide"):(a.style.display="none",b.innerHTML="show")} 
    //]]> 
    </script>
        
  5. Next search ]]></b:skin> and just above it paste the following CSS code:
    /*####TOC Plugin V2.0 by MyBloggerTricks####*/
    .mbtTOC2{border:5px solid #f7f0b8;box-shadow:1px 1px 0 #EDE396;background-color:#FFFFE0;color:#707037;line-height:1.4em;margin:30px auto;padding:20px 30px 20px 10px; font-family:Oswald, arial;display: block;width: 70%;}.mbtTOC2 button{background:#FFFFE0; font-family:oswald, arial; font-size:22px;position:relative; outline:none;border:none; color:#707037;padding:0 0 0 15px;}.mbtTOC2 button a {color:#0080ff; padding:0px 2px;cursor:pointer;} 
    .mbtTOC2 button a:hover{ text-decoration:underline; } 
    .mbtTOC2 button span {font-size:15px; margin:0px 10px; }
    
    .mbtTOC2 li{margin:10px 0;  } 
    .mbtTOC2 li a {color:#0080ff; text-decoration:none; font-size:18px; text-transform:capitalize;} 
    .mbtTOC2 li a:hover {text-decoration: underline;}.mbtTOC2 li li {margin:4px 0px;} 
    .mbtTOC2 li li a{ color:#289728; font-size:15px;}
    
    .mbtTOC2 ol{counter-reset:section1;list-style:none}
    .mbtTOC2 ol ol{counter-reset:section2}
    .mbtTOC2 ol ol ol{counter-reset:section3}
    .mbtTOC2 ol ol ol ol{counter-reset:section4}
    .mbtTOC2 ol ol ol ol ol{counter-reset:section5}
    .mbtTOC2 li:before{content:counter(section1);counter-increment:section1;position:relative;padding:0 8px 0 0;font-size:18px}
    .mbtTOC2 li li:before{content:counter(section1) "." counter(section2);counter-increment:section2;font-size:14px}
    .mbtTOC2 li li li:before{content:counter(section1) "."counter(section2) "." counter(section3);counter-increment:section3}
    .mbtTOC2 li li li li:before{content:counter(section1) "."counter(section2) "."counter(section3) "." counter(section4);counter-increment:section4}
    .mbtTOC2 li li li li li:before{content:counter(section1) "."counter(section2) "."counter(section3) "." counter(section4)"." counter(section5);counter-increment:section5}
    /* 
    .point2 {list-style-type:lower-alpha} 
    .point3 {list-style-type:lower-roman} 
    .point4 {list-style-type:disc} 
    */
        

    Make these custom changes if you want:

    • To change background color of container box edit #FFFFE0
    • To change border color of the box edit #f7f0b8
    • To change font color of the headline text edit #707037
    • To change anchor link color edit #0080ff
    • To change link hover color edit #289728
    • If you would like to show the alpha-numeric & roman list style then delete the green highlighted chunk of code and also the two yellow highlighted lines. This will remove the nested numbered list and replace it with alpha-numeric.
  6. Finally search for <data:post.body/> and replace it with the code below:

    Note: You will find this code two or more times inside your template, so replace all its instances with the code below especially the second occurrence. TOC Plugin will not work if you replace <data:post.body/>  just once.

    <div id="post-toc"><data:post.body/></div>
  7. Save your template and you are all done!

How To Show TOC Inside a Post or Page?

Add TOC to only those blog posts which are long and lengthy in length with several subheadings. Adding it to a blog post with just three or less headings does not make sense.

You can add a dynamic TOC inside a blog post in two easy steps.

Step #1 Mention Location Of TOC Container

It is best to display TOC right after your starting paragraph or show it before the first heading on your blog post.

To do this, switch to "HTML" mode of blogger editor and then paste the following HTML code just before the first heading.

<div class="mbtTOC2"> 
<button>Contents <span>[<a onclick="mbtToggle2()"  id="Tog">hide</a>]</span></button> 
<div id="mbtTOC2"></div> 
</div>

 

Step #2  Call The TOC Function

Finally, its time to invoke the plugin so that it could auto-generate a TOC on page load,

To do this, paste the following JS code at the bottom of your blogger editor where your post ends:

<script>mbtTOC2();</script>

Publish your post and see it in action! :)

Copyrights

Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

© 2008-2017 MyBloggerTricks.com
Version: 2.0  2017/02/27

TOC Plugin by MyBloggerTricks (MBT) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

You are most welcomed to share the plugin with your readership as long as you attach credit link back to this page. You are most welcomed to use the plugin in your commercial products as long as you keep the source credits intact.

Feedback

Would love to hear your thoughts on this major upgrade. Let me know if it lived up to your expectations. :)

I tried my best to create an SEO friendly and extremely lightweight script to the best of my ability. I hope it may add a new soul to your content and give it a big push in SERPs.  Share it with your friends and #JavaScript lovers!

Let me know if you need any help or further clarification with any part of this tutorial. Would love to help as soon as time allows.

Need Quick Help within 24 Hours? ASK NOW



If you don't want to get yourself into Serious Technical Trouble while editing your Blog Template then just sit back and relax and let us do the Job for you at a fairly reasonable cost. Submit your order details by Clicking Here »

24 comments : Post Yours! Read Comment Policy ▼
PLEASE NOTE:
We have Zero Tolerance to Spam. Chessy Comments and Comments with 'Links' will be deleted immediately upon our review.

  1. Hi! Thanks for such great and simple script!
    Could you help with usage it on HTML5 static site usage.
    How can this script generate TOC after some specific tag in HTML, for example, generating TOC after /hr class="sep"/ tag inside main content?

    ReplyDelete
    Replies
    1. For doing that you simply need to use this method:

      .getElementsByTagName("hr")

      The script will need some major changes to make it work.

      Delete
  2. the older version works perfect but this version not working. it is not showing the list only shows heading content and not the list. I have double checked the whole installation but still problem not fixed. you can check here: http://www.ratta.pk/2017/02/poverty-in-pakistan-english-essay.html

    ReplyDelete
    Replies
    1. you are using too many heading tags and instead of using unordered bullet lists you have used heading tags for every single headline which is not good from SEO stand of point.

      This way the TOC will tremendously increase your keyword density and your blog could look like a keyword spam.

      Please first format your posts. I suggest you better stick to version 1.0. Because version will only pick H2 and ignore other heading tags. This is best use in your case

      Delete
  3. Awesome work, that’s what I was looking for a long time.
    Thanks Brother.

    ReplyDelete
    Replies
    1. When we click the heading, It scrolls directly without any animation, Is there any way that it will scroll smoothly?

      Delete
    2. for smooth scrolling we can use jQuery or some extra lines of JS and that is what I did not want because then it would not be called a light script. U

      Visitors honestly don't care about these animations, all they care is instant load time.

      Delete
  4. Such a good and informative article. It gave me unique information which i can apply for my blog.

    ReplyDelete
  5. thanks Mustafa
    TOC is a jQuery-free JavaScript plugin that automatically generate a table of contents from HTML heading tags of ... Returns an ordered-list of headers in page content. ... Create A Multi-Level Drop Down Menu with Pure CSS.

    ReplyDelete
  6. This is amazingly described by you. Thanks

    ReplyDelete
  7. Here a tip from my Side. To create an animation add below CSS.

    h2:target {
    animation: highlight 1s ease;
    }
    @keyframes highlight {
    from { background: yellow; }
    to { background: white; }
    }

    ReplyDelete
  8. Hey, I don't know where to post suggestions, but it would be cool if you could write a tutorial about how to code your blog to look/work better on a mobile phone. Have you already done that? I have a social media-type blog and it would be nice if my friends could use it on their phones. I have used a whole bunch of your tutorials. Thanks for your hard work!

    ReplyDelete
  9. Hi Bhai
    I have a question. I don't use H2 in blog post. I use H3 (i.e. Sub heading). So how should I apply TOC in my blog post?

    Also, tell me bro, what is the benefit of using H2 over H3?

    ReplyDelete
  10. Salam Mustafa Bhai,
    The previous version of TOCplugin work well on my blogger site But when I try this version only the header "content" text is shown. Please have a visit of my site and kindly solve this issue. Thanks (site:http://www.buzzytricks.com )

    ReplyDelete
  11. How can i insert content heading in TOC

    ReplyDelete
  12. Its doesn't seems to be working on my blog. Can you please check why?
    http://www.thepacificminds.com/2017/09/test.html

    ReplyDelete
  13. The TOC is working just perfectly. Most often it does not work when might have added multiple instances of jQuery library or have not properly added all JS code on your site below the head tag or above the closing body tag.

    ReplyDelete
  14. I did a trial but it did not work...any suggestions??
    http://www.thephdguy.com/p/blog-page_12.html
    Thanks in advance!

    ReplyDelete
  15. Hello Mohammad Sir
    Finally you have invented this Plugin in blogger platform. and it is working in google where it shows jump to. Now i am using this Java script in my blogger and it is working properly.

    But i have a issue on this. When you will see TOC plugin in Wordpree (hide) option it is not similar to your TOC Plugin In blogger. The Script area is not same. please have a look on this.
    Thanks

    ReplyDelete