For longer articles it’s generally a rule to include a table of contents and this doesn’t exclude SharePoint. SharePoint has a capability to create an anchor link for some page types but it’s a repetitive and error-prone process for end users. In this post, we’ll take a look at how you can automatically generate a table of contents for your items.
Traditionally, you would use a custom page layout where your table of contents would be defined as a DIV of some sort; in this example, for simplicity we’ll just use 2 content editor web parts.
We’ll be using jQuery to build this example so make sure you reference the latest version of jQuery.
We’ll start by adding a content editor web part to the top of the page:
1. Add a content editor web part to the top of the page
2. Chose to enter markup directly into the web part using ribbon HTML -> Edit HTML source fly out
3. Enter the following
<div id="toc"></div>
Now, onto the script:
1. Add another content editor web part to the bottom of the page
2. Chose to enter markup directly into the web part using ribbon HTML -> Edit HTML source fly out
3. Enter the following
<script>
$("#toc").append('<p id="tocHeader">In this post:</p>')
$("h2, h3").each(function(i) {
var currentNode = $(this);
currentNode.attr("id", "title" + i);
$("#toc").append("<a id='link' +i + "' href='#title" + i + "' title='" currentNode.attr("tagName") +"'>" + currentNode.html() "</a></br>"
currentNode.append(" <a href='#tocHeader'>[back to top]</a>")
</script>
Basically the script above will parse the page for h2 and h3 tags and take their text to the top of our table of contents. Also, the script will add a link to the table of contents right from the h2 or h3 header.
More branding tips and tricks like this one check out my SharePoint branding book
Enjoy!


