Hack #71. Add a Table of Contents to Long Pages

Create a menu out of a page's header tags.

I read a lot of specifications online. Not as part of my day job; I mean I do this for fun. There are good specifications, and there are bad specifications, but there is one thing you can say about virtually all of them: they are incredibly long. And most of them are published online as a single HTML page. Firefox's incremental find feature helps when I'm trying to find something specific (just press Ctrl-F and start typing), but I still often get lost in the endless scrolling.

One nice thing about W3C specifications in particular is that they use HTML correctly. Section and subsection titles are marked up with header tags: <h1>, <h2>, <h3>, <h4>, and so on. This hack takes those header tags and creates an in-page table of contents. Using the same technique as "Add an Access Bar with Keyboard Shortcuts" [Hack #68] , the script adds a fixed bar at the bottom of the browser window that contains a drop-down menu of all the headers on the page. Selecting a header from the menu jumps directly to that section on the page.

The Code

This user script runs on all pages. It iterates through all the <h1>, <h2>, <h3>, and <h4> elements on the page, and creates a <select> menu in a fixed-position bar along the bottom of the browser window, just above the status bar. Items in the menu are indented based on the header level, so when you drop down the menu, it appears to be a hierarchical table of contents. ...

Get Greasemonkey Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.