Tag: scrolling

In the project I’m currently working on we are creating a solution in SharePoint 2013 for content that previously has been in word documents. The content is very text-focused, and consists almost entirely of headings and text blocks. We are using enterprise wiki as the new home for the content in SharePoint.

One of the “key features” of the documents (and Word-documents in general) are the table of contents, where you get quick links to the sections you are interested in. This was a feature we wanted to have in SharePoint as well, and what’s better than having the table of contents auto-generated to avoid ToC’s that needs to be manually updated and often go stale.

The solution is pretty simple. In the page layout we’re using, I’ve added a header and an empty unordered list.

The Javascript

When the DOM is ready, we’re calling a nice little function that iterates over all the h1 and h2 tags in the document, adds anchor bookmarks to the headings and adds the headings to the table of contents. To make it somewhat more reusable, the function takes the selector of the table of contents list element and the selector of the section we are looking for headers in.

The looks of it

Which creates a table of contents that looks similar to the image in the top of this post (there are some other css styles defined which are not relevant).

Back to the top

When the user gets to the bottom of the page, he most likely would love to go the top again. Hence I’m adding a simple bookmark-link to go to the top of the page after the content section.

<a href="#top">To the top</a>

That’s basically it! The solution would work fine as it is now.

Bonus: Smoothscrolling

Wouldn’t it be great if the browser scrolled smoothly down to the sections we cared about instead of skipping down instantly? This way it’s more clear to the user what happens at the click of the button.

Smoothscrolling in SharePoint apparently wasn’t that easy . I’m going to spare you the details, but the final solution I ended up with was the one discussed and improved over at the technet forums. I did some minor modifications to the script discussed there, and came up with the following function which I’m calling after generating the Table of Contents.

After the scrolling has happened I still want the #bookmark in the URL, in order to allow directly linking to sections as well as back and forth functionality in the browser. That’s why I’m setting window.location.hash = hashVal.