Create Auto Table of Contents jQuery Plug in - autoToc.js

- September 12, 2018
jQuery plug-in to auto generate Table of Contents based on the h2 headings available in the article tag of HTML document.

Features

  • Smooth scrolling between sections.
  • Fully customizable with CSS.
  • Lite weight file size.
  • Simple and clean logic.
  • User friendly and Easy to implement.

How to Use

Just call the autoToc() in your jQuery code, use the HTML selector, where Table of Contents to be inserted. For example, if you want to append this TOC in the beginning of your article, the statement will be:

 $("article").autoToc(); 

Similarly, you can insert this autoToc anywhere, i.e in the sidebar , or your desired location.
No need any extra tag, coding or anything more...


Step by Step Implement Guide

1. Import both jQuery JavaScript library and the jQuery autoToc.js library into the html.

<!--jQuery-->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" 
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" 
        crossorigin="anonymous">
</script>
<!--autoToc.js-->
<script src="js/autoToc.js"></script>

2. Create a container in which the table of contents will be generated.

<div class="at"></div>

3. Split your article into several sections using h2 tag.

 <article>
  <h2> Section 1 </h2>
  ... Content 1 ...

  <h2> Section 2 </h2>
  ... Content 2 ...

  <h2> Section 3 </h2>
  ... Content 3 ...

  More Sections Here
</article>

4. The JavaScript to generate an ordered list based table of contents in the document.

$(document).ready(function(){
   $(".at").autoToc();
});

5. The example CSS to style the table of contents.

.auto-toc {
  background: #f2f2f2;
  padding: 15px;
  margin: 15px;
  border-radius: 4px;
}

.auto-toc ol{
  padding: 10px;
}

.auto-toc ol li{
  margin-left: 10px;
  padding: 0px;
  box-sizing: border-box;
}

.auto-toc ol li a{
  text-decoration: none;
  color: #348781;
  display: block;
  border-bottom: 1px dotted rgba(0, 0, 0, 0.1);
  padding: 10px;
}

.auto-toc ol li a:hover{
  background: rgba(0, 0, 0, 0.095);
}

.auto-toc h4 {
  font-size: 15pt;
  text-align: center;
}