1

I have a document on my wiki page with multiple nested headings and I want them to be displayed as a Table of Contents (TOC) at the start of every page.

h1 Component description
    h2 About
    h2 Usage
       h3 Install
       h3 Configuration
       h3 Startup

Every page has different headings and thus will have a different TOC.

I have used the existing Table of Contents web part but it only lists all documents in my project and displays them as a TOC.

Is there a way to achieve it to behave like in Office.

Here is an example what I want to achieve but in confluence

Any advice would be appreciated.

2 Answers 2

1

This can be achieved via simple jQuery. All you need to do is to add the following script in your page layout or a Content Editor Web Part.

<script type="text/javascript">
            $(document).ready(function(){
                $(".ms-rtestate-field h1,.ms-rtestate-field h2,.ms-rtestate-field h3,.ms-rtestate-field h4").each(function(){
                    if($(this).is("h2"))
                    {
                        if($(this).text()!=" ")
                        {
                            $("#wiki-index").append("<a style='margin-left:20px;' href='#"+$(this).text()+"'>"+$(this).text()+"</a>")
                        }
                    }
                    if($(this).is("h3"))
                    {
                        $("#wiki-index").append("<a style='margin-left:40px;' href='#"+$(this).text()+"'>"+$(this).text()+"</a>")
                    }
                    if($(this).is("h4"))
                    {
                        $("#wiki-index").append("<a style='margin-left:60px;' href='#"+$(this).text()+"'>"+$(this).text()+"</a>")
                    }
                    if($(this).is("h1"))
                    {
                        $("#wiki-index").append("<a href='#"+$(this).text()+"'>"+$(this).text()+"</a>");
                    }
                    $(this).prepend("<a name='"+$(this).text()+"'></a>");
                })

            });     

        </script>

Next, you would need to define an area to display your TOC, for this you would need to add a div

<div id="wiki-index">
                    <div class="toc">Table of Contents</div>
                </div>

After adding this script and div, when you insert headings in your wiki content h1, h2, h3, h4, this script would auto-generate a TOC upon saving your wiki page.

1

I would use jQuery for this "dynamic" task. Something like this: https://jsfiddle.net/dinoskon/rr0rz2qb/1/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.