Simple Table Of Contents in JQuery
I developed a handy Table of Contents script using JQuery for another project, now abandoned, and I decided to implement it on this website (which uses WordPress). This assumes that you have JQuery already loaded and are using WordPress 2.9 or newer.
How To Do It
- Make sure that your theme uses the new
body_class()template tag. If it is, the HTML should read something like this:- <body class="single postid-842 logged-in">
If it doesn’t, edit
header.phpto make the tag look something like this:- <body <?php body_class(); ?>>
Note: This could very well muck up your theme if it uses CSS classes (e.g.
date) for other purposes. Be sure to test everything carefully after this step. - Copy the following JQuery script into a file in your template directory called
js/toc.js:- jQuery(function () {
- var started = false;
- jQuery("body.single .entry h2").each(function (index) {
- // Create div if needed
- if(!started) {
- jQuery('body.single .entry').prepend('<div id="intlinks"><a name="top"></a><p><strong>On this page:</strong></p><ul></ul></div>');
- started = true;
- }
- // Manipulate h* tag
- var header = jQuery(this);
- var headerId = 'header-'+index;
- header.attr('id', headerId);
- // Manipulate list
- var li = jQuery('<li></li>').appendTo('#intlinks ul');
- jQuery('<a></a>').text(header.text()).attr({ 'title': 'Jump to '+header.text(), 'href': '#'+headerId }).appendTo(li);
- });
- jQuery('body.single .entry h2').wrapInner('<a title="Back to top" href="#top"></a>');
- });
If this doesn’t work for you for some reason, you might need to change
body.single .entryin the script above to be the correct CSS selector for the contentdivof your theme. - Next, edit
header.phpand include this line near the end (after the call towp_head()):- <?php if(is_single()) : ?><script type="text/javascript" src="<?php bloginfo('template_url') ?>/js/toc.js"></script><?php endif; ?>
Add Some Style
Now that you’ve got the Table of Contents working, it’s time to style it. Here’s a very simple example from this site:
- #intlinks {
- width: 150px;
- float: right;
- margin: 10px;
- padding: 10px;
- background-color: #FFEEEE;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- border-radius: 5px;
- }
Future Plans
If enough interest is shown in this, I’ll turn this into a WordPress plugin so that it is even easier to install. Be sure to let me know in the comments.


