Automatic Table Of Contents Generator - jQuery autoContents.js
File Size: | 3.59 KB |
---|---|
Views Total: | 701 |
Last Update: | |
Publish Date: | |
Official Website: | Go to website |
License: | MIT |

autoContents.js a jQuery plugin that automatically generates a table of contents from all h2
elements found within the document and puts it after the h1
element.
How It Works:
- Loop through every
<h2>
element within the document. - Assgin an unique ID to each
<h2>
element. - Generate an ordered list containing anchor links.
- Add the table of contents after the
<h1>
element.
How to use it:
1. Just insert the autoContents.js
script after loading the latest jQuery library and the plugin will do the rest.
<script src="/path/to/cdn/jquery.slim.min.js"></script> <script src="/path/to/autoContents.js"></script>
2. Feel free to modify the script to fit your needs.
var fullString = "<div id='tableofcontents'><h2>Table Of Contents</h2><ol>"; var ID = 0; $("h2").each(function () { ID++; element = $(this); content = element.text(); element.attr("id", ID); fullString += "<li><a href= #" + ID + ">" + content + "</a></li>"; }); fullString += "</ol></div>" $("h1").after(fullString);
This awesome jQuery plugin is developed by DennisFriedl. For more Advanced Usages, please check the demo page or visit the official website.