Javascript Table Of Contents

1 AM June 2, 2004

I have been putting together a static HTML site that has some long pages. It was becoming difficult to find content on some of these pages so I added an automagically generated table of contents.

The table of contents is generated from all H1, H2 and H3 headings on the page, except if there is only one heading, in which case the whole table of contents is removed.

My script is based on this article from quirksmode.org.

Here is the script:


// pageToc.js

//

// Ensure all H1, H2 and H3 headings are added to the page table of contents

//



window.onload = createTOC;



function createTOC()

{

  // find the nodes to be added to the Page TOC

  var tocTargets = new Array()

  nodes = document.getElementById('contentArea').childNodes

  for (var i = 0; i < nodes.length; i++) {

    nn = nodes[i].nodeName

    if (nn == "H1" || nn == "H2" || nn == "H3") {

      tocTargets.push(nodes[i])

    }

  }



  tocDiv = document.getElementById('pageToc')



  // Remove toc if none or one heading

  if (tocTargets.length <= 1) {

    tocDiv.parentNode.removeChild(tocDiv)

    return;

  }



  // Add the toc contents

  tocDiv = document.getElementById('pageToc')

  tocDiv.innerHTML= "<h2>Page Contents </h2>"

  tocList = document.createElement('ul')

  tocList.className = "pageToc"

  tocDiv.appendChild(tocList)

  // Insert elements into our table of contents

  for (var i = 0; i < tocTargets.length; i++) {

    tocTarget = tocTargets[i]

    if (tocTarget.id == '') {

      tocTarget.id = 'pageToc' + i

    }

    newItem = document.createElement('li')

    newItem.className = "pageToc" + tocTarget.nodeName

    newLink = document.createElement('a')

    newLink.href = '#' + tocTarget.id

    newLink.innerHTML = tocTarget.innerHTML

    newItem.appendChild(newLink)

    tocList.appendChild(newItem)

  }  

}



To use it, you need to add a reference to the script in each page header


<script src="/idsproj/theme/pageToc.js"></script>

This DIV element also needs to be added near the top of the body:


<div id="pageToc">

</div>

The script has been tested on Mozilla, Firefox and IE6. Feel free to use as you will, though I would appreciate a comment here if you do.

By alang | # | Comments (2)
(Posted to javablogs and Java)

Comments

At 11:49, 02 Jun 2004 Renaldy wrote:

Alan, you beat me to it!

Well done!

(#)
At 11:16, 19 Jul 2004 kalle wrote:

Hi, very good idea, but:
It won't work for me.
Do you have a URL to a webside where it is working?

thanks

(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green