Create Automatic Table Of Contents In JavaScript - TOC Plugin

Wikipedia loves adding an automatic Table Of Contents list for each article it publishes because it engages readers more by providing more accessibility and better navigation. Google prefers high-quality content which is well organized and formatted. Adding elements like tables, numbered sections, and an auto-generated TOC is a big bonus for ranking high in SERPS.

Update: TOC Plugin Version 2.0 has been released.  More advanced with more features!

TOC Plugin: Automatic Table of Contents using JavaScript

In this article, we will share a lightweight TOC plugin written in pure JavaScript to generate an automatic table of contents from the section headings of a web page. 

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

    What is Table Of Contents or TOC?

    In websites, a table of contents abbreviated as TOC or ToC, is a link list, usually found on a web page placed right after the first paragraph. Each anchor link inside a TOC takes you to a specific section of the web page.

    An HTML TOC provides a quick way to jump to the desired section of a page. It usually includes the titles of the first-level headers (headings) or second level headers(subheadings).

    Table Of Contents of a wikipedia page

    In printable work, a TOC refers to the index page of the book which contains the page number to each chapter. TOC for books are more in-depth and comprehensive, containing not only section titles but descriptions, author names, and subheadings.

    table of contents of a drawing book

    What Is TOC Plugin?

    TOC plugin developed by MBT, is an automatic solution to the tedious method of creating a table of contents manually for each web page. It auto-generates a user-friendly TOC for your lengthy blog articles. It is coded in pure JavaScript and loads lightening fast. Contents table generated using TOC plugin is easily crawled and indexed by search robots.

    • Read this interesting article by MOZ which mentions SEO support for all JS methods that we have used so far in building TOC plugin.

    SEO ALERT: Just minutes after this post was published. Google not only indexed the TOC  anchor Links but also added a "Jump to" label to identify that it is an anchor link that jumps to a particular section. See it to believe it. :)

     Table of contents anchor links indexed by Google

    I have not included lower level heading tags (i.e. h3/h4/h5/h6) in TOC plugin because a blog post is neither a wiki nor a long lengthy book, it is best to show only major headlines for simplicity and accessibility. Adding subheadings or lower levels inside a TOC list only makes it longer in length thus pushing down your main content and destroying visibility.

    Automatic Table Of Contents for blogger blogs

    So far many developers have written a dynamic ToC script but most of these scripts are either coded in jQuery or they are render-blocking JS eating up your page load time. You may even find TOC generator but these scripts again lack flexibility and ease of customization.

    TOC should be added only to those articles which are lengthy or contain at least four headings. On contrary, some TOC generators will add the list on all your pages whether containing several headings or just a single heading, which of course is not a sensible thing to do.

    jQuery table of contents is much slower compared to this plugin built with traditional pure JS. JavaScript is executed much faster by browsers compared to a JS library (jQuery) that needs to be imported first.

    Features of TOC Plugin:

    It is the first JavaScript plugin of its kind that is unique in several ways as mentioned below:

    • Coded in pure JavaScript - just 10 lines of code!
    • Lightweight and fast.
    • SEO Friendly
    • Adds unique ID to each section automatically.
    • Creates both ordered or unordered list
    • Contains a Toggle button
    • Show on any location you choose
    • Easily Customized
    • Mobile responsive
    • Executes only when invoked!

    Pseudo Code Of TOC Plugin

    Understand how the TOC Script works in plain English. The numbered list below is the pseudo code for our TOC plugin. It is a simplified description of the JavaScript code we wrote.

    Table Of Contents for blogspot blogs

    1. Create a function to print headline links
    2. Count the number of heading sections on a page
    3. Run a loop equivalent to the number of heading sections
    4. Extract text content from the heading titles
    5. Give each heading a different ID
    6. Convert the heading text into an anchor link
    7. Print the heading anchor links inside a bullet list
    8. Find the location by TOC ID to display the list
    9. End the loop
    10. Trigger the function only when invoked inside the page

    Table Of Contents with show/hide button

    Following is the pseudo code for the toggle button which shows or hides the TOC.

    1. Create a new function to show/hide the TOC.
    2. Show the TOC by default
    3. Use a conditional statement to check if TOC is hidden or visible.
    4. Use CSS to show or hide the TOC
    5. Trigger the function only when button is clicked

    How To Install TOC Plugin in Blogger Blogs?

    I am sharing below the method of adding TOC plugin in Blogspot blogs but you can apply almost the exact same method for installing this plugin on any website you want, may it be hosted on Wordpress or anywhere else.

    Follow these steps to install it in BlogSpot:

    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://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css' rel='stylesheet'/>
      <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'/>

      <script type='text/javascript'>
      //<![CDATA[

      //*************TOC plugin by MyBloggerTricks.com
      function mbtTOC() {var mbtTOC=i=headlength=gethead=0;
      headlength = document.getElementById("post-toc").getElementsByTagName("h2").length;for (i = 0; i < headlength; i++)
      {gethead = document.getElementById("post-toc").getElementsByTagName("h2")[i].textContent;document.getElementById("post-toc").getElementsByTagName("h2")[i].setAttribute("id", "point"+i);mbtTOC = "<li><a href='#point"+i+"'>"+gethead+"</a></li>";document.getElementById("mbtTOC").innerHTML += mbtTOC;}}function mbtToggle() {var mbt = document.getElementById('mbtTOC');if (mbt .style.display === 'none') {mbt .style.display = 'block';} else {mbt .style.display = 'none';}}
      //]]>
      </script>

      Note that I am adding source links to Oswald font and Font-Awesome for styling purposes. You may or may not wish to add them. The code inside purple highlighted lines is the major TOC script in no more than 10 lines!

      Make this change only if needed:

      The major heading tag in blogger is H2 but if you are selecting the subheading tag in blogger editor then your default tag would be H3. If you are using the subheading tag as your main heading in your blog posts then please replace h2 with h3 thrice in the code above.  TOC plugin will not work if your heading tag is not correct.

    5. Next search ]]></b:skin> and just above it paste the following CSS code:
            

      /*####Automatic TOC Plugin by MyBloggerTricks####*/
      .mbtTOC{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%;}
      .mbtTOC ol,.mbtTOC ul {margin:0;padding:0;}
      .mbtTOC ul {list-style:none;}
      .mbtTOC ol li,.mbtTOC ul li {padding:15px 0 0; margin:0 0 0 30px;font-size:15px;}
      .mbtTOC a{color:#0080ff;text-decoration:none;}
      .mbtTOC a:hover{text-decoration:underline; }

      .mbtTOC button{background:#FFFFE0; font-family:oswald, arial; font-size:20px;position:relative; outline:none;cursor:pointer; border:none; color:#707037;padding:0 0 0 15px;}
      .mbtTOC button:after{content: "\f0dc"; font-family:FontAwesome; position:relative; left:10px; font-size:20px;}

      Make these color changes if you want:

      • To change background color of TOC box edit #FFFFE0
      • To change border color of TOC box edit #f7f0b8
      • To change font color of TOC headline text edit #707037
      • To change anchor link color edit #0080ff
      • To change font size of anchor links edit 15px
      • To change font size of TOC headline text edit 20px
    6. Finally search for <data:post.body/> and replace it with the code below:

      Note: You will find two or more occurrences of this code so replace all its instances with the code below. 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!

    Show Table Of Contents Automatically in Blog Posts

    Each time you may want to display TOC inside a specific post, follow these two 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 or anywhere else you may want.

    <div class="mbtTOC"> 
        <button onclick="mbtToggle()">Contents</button> 
        <ol id="mbtTOC"></ol> 
        </div>
    
    • You can replace the text "Contents" with any other text you may like.
    • If in case your headings already contain numbers in beginning then replace ol with ul.

    Add Table Of Contents automatically in blog posts

    Step #2    Activate TOC Plugin

    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>mbtTOC();</script>
    

    Invoke TOC plugin

    Publish your post and see the magic! :)

    TOC Plugin Copyrights

    Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

    © 2008-2017 MyBloggerTricks.com
    Version: 1.0  2017/02/14

    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 attribution 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.

    Need Help With TOC Plugin?

    I tried my best making this tutorial as easy as possible but if there is anything you could not understand then please feel free to post your queries below in the comment section. I would love to answer as soon as possible.

    I hope it adds a positive impact on your SERPS ranking and help you in making your content more search-friendly. I will develop the plugin with time, adding more features and functionalities if required. Till then, I would love to hear your feedback on this.  :)

    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 »

    62 comments

    PLEASE NOTE:
    We have Zero Tolerance to Spam. Chessy Comments and Comments with 'Links' will be deleted immediately upon our review.
    1. Assalamualaikum!! Aswesome bhai, much awaited plugin for blogger... Thanks alot for sharing...

      ReplyDelete
      Replies
      1. W.salam dear Sharfuddin,

        A pleasure buddy. Pleased to help :)

        Delete
    2. My goodness...What an awesome detailed tutorial...!!!
      Thanks Mohammed Mustafa...!!
      Good to see you are sharing WordPress kind of plugins for the blogger platform too...!!
      Keep making such plugins...

      ReplyDelete
      Replies
      1. A pleasure dear. I have created several such plugins, the famous being "Blogger Shortcodes" and "Json Feed API Plugins". Coding is all that I love buddy and it feels great when you find such guides useful.

        Thank you for the kind feedback Navin buddy :)

        Delete
    3. Thanks a lot bhai ur really awesome.

      ReplyDelete
    4. Very Nice post, i am working on adding it to my blog

      ReplyDelete
    5. Can You Create a GADGET For this ????

      It will be easy for US (Newbies) coz we don't want to edit template unnecessarily.

      I tried this on http://www.manywish.com didn't worked. :(

      ReplyDelete
      Replies
      1. adding a widget will effect your load time and is not recommended. I visited your site and did not find the codes. Please add it and let me know I will mention how to fix it on your site

        Delete
    6. master, how to make site map? cou'z feed api google is shut down :D

      ReplyDelete
      Replies
      1. you mean something like this: "Blogger Sitemap TOC"

        JSON Feed API is working just fine. What problem are you facing buddy?

        So glad hearing from you after so many years :)

        Delete
      2. oops, my false! i'm host the file on google drive.
        LoL
        Cheers \m/

        Delete
    7. which font you are using on your post title

      ReplyDelete
    8. SEO Update:
      ============
      Check this buddies :)

      [img src="https://lh3.googleusercontent.com/-7AkWAHNXxos/WKQv9ZY5ZaI/AAAAAAAARfI/Vkvm9zStB4w/image%25255B7%25255D.png?imgmax=800" width="95%"/]

      ReplyDelete
    9. hi,thanks Mustafa for this awesome information

      ReplyDelete
    10. thanks a lot bhaijaan its working fine

      ReplyDelete
    11. Hi Mohammad bro,

      Wow bro. I wish I'd known JavaScript. With JavaScript, doing things in Blogger are so simple. By the way, thanks for creating such widgets. These codes help me to learn JavaScript. ^_^

      Amazing as always. Got something to utilize. :)

      ReplyDelete
      Replies
      1. So glad hearing from you dear Shivansh. Where have you been? :)

        Indeed JavaScript is the best tool when it comes to front-end programming and trust me its too easy to learn. Just watch some videos at lynda.com and that's it! :)

        hey Shivansh why not you different color themes of this plugin with your audience because CSS is what you are too best at! This will help people more. Just an idea.

        Delete
      2. "Got something to utilize."

        I was talking about the same. ;)

        Will ping you soon about it. (^^)

        Delete
    12. I tried to use it on my website http://www.hutiya.net/ but after adding all the codes and updating code in post. It didn't worked then I removed the code.
      There might be some problem with it. Please fix it.
      Regards
      Anmol Singhi

      ReplyDelete
      Replies
      1. Another guy was using exact similar template as yours and it worked for him.

        I checked your blog and this is what you need to do.

        1) Since you are not using H2 tag for headlines but h1 which does not make sense. Therefore kindly either use h2 or h3 tags for your headings. If you are using h3 tag then replace all h2 tags in STEP#4 with h3.

        2) For step#6, you will find data:post.body twice or thrice. So replace it multiple times with the code I shared and not just once.

        Without these fixes, obviously the plugin wont work. You need to install it as instructed.

        Delete
    13. Asa Mustafa,

      Thanks for such a detailed and well-crafted tutorial.

      May I know which screenshot app you used for this post?

      Is it Skitch?

      Keep up the great work.

      ReplyDelete
      Replies
      1. W.salam buddy,

        I simply press the keyboard button of "PrntScr" and then paste the image in Open Live Writer. That's it! :)

        Delete
      2. I'm actually curious about the orange arrows you've used in your screenshots.

        Is there a tool for this?

        Delete
    14. Hey, Mustafa bro.

      It's just awesome dear. I knew, you could do it and that's why I requested you for this awesome widget.

      I was shocked that time when you tagged me after coding + publishing above guide. You did it very next day after my request.

      I'm late to comment because I was busy in family work. So sorry for that.

      Once again thanks a lot dear. You're really awesome. <3 :)

      ReplyDelete
      Replies
      1. You are most welcomed dear paramoj and thank you for bringing up this great idea. This could have never been done without you and I do thank you for that. :)

        I love coding buddy and that's what I can't quit :)


        I just noticed that you are also running a site on blogger guides, why not share this plugin with your readers dear paramjot?

        Would love to see you here often!

        Delete
    15. your great Mohammad mustafa sir.your blog is very helpful.

      ReplyDelete
      Replies
      1. Thank you Jalil. I am trying to be more punctual with posting. Thank you for the kind feedback :)

        Delete
    16. Hello! Can you do a post on how to customize your blog's cursors?

      ReplyDelete
    17. Thankx, i am working on adding it to my blog

      ReplyDelete
    18. This one is really helpful bro :)

      Going to try.

      -Ashutosh

      ReplyDelete
    19. The contribution for Blogspot community from your side is just unforgettable. Where everyone is focusing on wordpress, People like you are doing things which could not have done till yet. While there are many talented people who can do it, But you are just awesome and your contribution too.
      Thank you

      ReplyDelete
      Replies
      1. Deepak this is probably the best feedback I received this year! :)

        Thank you for considering a small man like me worth your kind words. Helping others with the limited knowledge I have is all that I aim in life. I am extremely grateful for all these precious words. God bless you buddy.

        Delete
    20. Please add h3 & h4 support with h2

      please..........bro like wikipedia

      i would be thankful to you.

      ReplyDelete
      Replies
      1. Already done! Just waiting to get some time to post it. :)

        Delete
    21. brother thanks for this awasame update . brother can you make an article how to use animated.css for next update . there many site but no one give information like this blog. thankyou.

      ReplyDelete
      Replies
      1. I would love to write on it someday because readers often ask me how I animate images. Thank you for the request :)

        Delete
    22. thanks sir for this awesome trick.. now my blogger blog will be in High Serp

      ReplyDelete
    23. Thanks a lot bhai ur really awesome.

      regards from iliyas shaikh

      ReplyDelete
      Replies
      1. So pleased to receive your comments after years! Where have you been iliyas :)

        Delete
    24. Thank you everyone for finding it useful. :)

      UPDATE:
      Based on your requests I have created the multi-level TOC plugin where you can display H1, h2, h3, h4 till h6.

      The new version will automatically pick headlines from your blog posts so no need to edit the code like we did for h2 in this version.

      Will publish it shortly.

      Anyone who wish to share it with his readers can surely do so by attaching attribution to this page.

      ReplyDelete
      Replies
      1. I am waiting for it bro :) hope you comeup with that very soon....

        Delete
    25. Hello Mustafa sir,
      Nice post. How to learn javascript and ajax about blogger ? Can you share some resources with us ?

      ReplyDelete
      Replies
      1. For that follow the JSON tutorials from this section.

        Blogger JSON Feed API

        Work on your JavaScript and Ajax skills at w3schools.com

        Delete
    26. I am waiting for plugin update for all heading tags support. bro... :(

      ReplyDelete
    27. WOW!!!!!! Awesome :) I loved it!

      Thank you so much! Mohammad Mustafa Ahmedzai Bhai :)

      You fullfilled my request :)

      God bless you! :)

      ReplyDelete
    28. It not works on my blog gyansagar999.blogspot.com ! Please guide to fix the error .

      ReplyDelete
    29. Thank you so much for this script. It works perfectly. But how to hide it from the summary of the post extracted for display on pages?

      ReplyDelete
    30. Thank you very much for providing this 😃, Now I am feeling proud to be a blogger user 😃. Please suggest me the best Tech theme for my blogger blog (https://www.glanceinfo.com) 😊

      ReplyDelete
    31. This TOC conflict with accordion shortcode, and showing double list. Thank you so much for this script, You Are Awesome!

      ReplyDelete
    32. How to change link #point0 to #point1 ?

      How to remove #point0 ?

      ReplyDelete
    33. Yup Sorry, It Working Perfectly thanks

      https://whoopmeloud.blogspot.in/p/hide-show.html

      ReplyDelete
    34. Thanks for the tricks.

      But it would be nice if you add one more level (h3) to the toc so people can learn more from your code, in case someone want to customize it to suit their contents.

      A lot more people will appreciate your work.

      ReplyDelete