Build a Dynamic Table of Contents with jQuery
There are plenty of jQuery plugins available that can generate a Table of Contents on an HTML page. But, I wanted to roll my own simple script with a few lines of jQuery.
What I wanted to build
- Dynamically create a Table of Contents (ToC) at the top of my HTML page
- Link the ToC items to any
<h1>elements inside a container (
#blogContents) on the page
- Assumption: H1 elements always have an id attribute (as they are generated using Jekyll)
Writing the script
As I mentioned, this plugin will use jQuery, so include that to start.
- Start by finding all the h1 elements inside the
- For each
<h1>we set a variable that gets the id and the text inside the tag.
- Then, we can write a string that generates a link (
<a>) for each, setting the href, title and text attributes.
- Append each
<a>to a list item (
- The list items are then appended into a specified
<ul>container element - this gives us our list of contents.
Make sure you include the
<ul> container in your page where you want your ToC to appear.
If you don’t have any
<h1> tags in your container you will end up with an empty
<ul> container sitting on your page. If you don’t want that, you can alternatively check to see if the page conatins any h1 elements, if there are, the following script will create the ToC container automatically - ready for your list of contents to be appended.
If you use this method, you need to make sure that this script runs BEFORE we generate the list of contents.
See the Pen Quick and Dirty Table of Contents with jQuery (ToC) by Matthew Elsom (@matthewelsom) on CodePen.