Hack 71. Add a Table of Contents to Long Pages

 < Day Day Up > 

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.

8.6.1. 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. Finally, we add a Hide TOC button on the right side of the table of contents bar. Clicking Hide TOC hides the bar temporarily until you refresh the page or follow a link to another page.

Save the following user script as autotoc.user.js:

 // ==UserScript== // @name AutoTOC // @namespace http://runeskaug.com/greasemonkey // @description Creates a table of contents for all headers on the page // @include * // ==/UserScript== // based on code by Rune Skaug // and included here with his gracious permission //set the optional behaviour of the TOC box // - true resets it to its initial state after you have selected a header // - false does not reset it var resetSelect = false; //if true, shows a "Hide TOC" button on the right side of the bar var showHide = true; var hideText = "Hide TOC"; function f( ) { // only on (X)HTML pages containing at least one heading - // excludes XML files, text files, plugins and images if ( document.getElementsByTagName("html").length && (document.getElementsByTagName('h1').length ||  document.getElementsByTagName('h2').length ||  document.getElementsByTagName('h3').length ||  document.getElementsByTagName('h4').length )) {   var aHs = getHTMLHeadings( );   if (aHs.length>2) { // HTML document, more than two headings.   addCSS( '#js-toc {position: fixed; left: 0; right: 0; top: auto; ' + 'bottom: 0; height: 20px; width: 100%; vertical-align: ' + 'middle; display: block; border-top: 1px solid #777; ' + 'background: #ddd; margin: 0; padding: 3px; ' + 'z-index: 9999; }\n#js-toc select { font: 8pt verdana, ' + 'sans-serif; margin: 0; margin-left:5px; ' + 'background-color: #fff; color: #000; float: ' + 'left; padding: 0; vertical-align: middle;}\n' + '#js-toc option { font: 8pt verdana, sans-serif; ' + 'color: #000; }\n#js-toc .hideBtn { font: 8pt verdana, ' + 'sans-serif; float: right;' + 'margin-left: 5px; margin-right: 10px; padding: 2px 2px; ' + 'border: 1px dotted #333; background-color: #e7e7e7; }\n' + '#js-toc .hideBtn a { color: #333; text-decoration: none; '+ 'background-color: transparent;} ' + '#js-toc .hideBtn a:hover { ' + 'color: #333; text-decoration: none; background-color: ' + 'transparent;}' ); var toc = document.createElement( showHide?'tocuserjselem':'div'); toc.id = 'js-toc'; tocSelect = document.createElement('select'); tocSelect.addEventListener("change", function( ) { if (this.value) { if (resetSelect) { this.selectedIndex = 0; } window.location.href = '#' + this.value; }  }, true);  tocSelect.id = 'navbar-toc-select';  tocEmptyOption = document.createElement('option');  tocEmptyOption.setAttribute('value','');  tocEmptyOption.appendChild( document.createTextNode('Table of Contents'));  tocSelect.appendChild(tocEmptyOption);  toc.appendChild(tocSelect);  if (showHide) { var hideDiv = document.createElement('div'); hideDiv.setAttribute('class','hideBtn'); var hideLink = document.createElement('a'); hideLink.setAttribute("href","#"); hideLink.addEventListener('click', function(event) { document.getElementById('js-toc').style.display = 'none'; event.preventDefault( ); }, true); hideLink.appendChild(document.createTextNode(hideText)); hideDiv.appendChild(hideLink); toc.appendChild(hideDiv); } document.body.style.paddingBottom = "27px"; document.body.appendChild(toc); for (var i=0,aH;aH=aHs[i];i++) { if (aH.offsetWidth) { op = document.createElement("option"); op.appendChild(document.createTextNode(gs(aH.tagName)+ getInnerText(aH).substring(0,100))); var refID = aH.id ? aH.id : aH.tagName+'-'+(i*1+1); op.setAttribute("value", refID); document.getElementById("navbar-toc-select").  appendChild(    op);  aH.id = refID;   }     }       } } GM_registerMenuCommand('AutoTOC: Toggle display', autoTOC_toggleDisplay);  };  function autoTOC_toggleDisplay( ) { if (document.getElementById('js-toc').style.display == 'none') { document.getElementById('js-toc').style.display = 'block'; } else { document.getElementById('js-toc').style.display = 'none';      }  }  function getHTMLHeadings( ) { function acceptNode(node) { if (node.tagName.match(/^h[1-4]$/i)) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_SKIP; } outArray = new Array( ); var els = document.getElementsByTagName("*"); var j = 0; for (var i=0,el;el=els[i];i++) { if (el.tagName.match(/^h[1-4]$/i)) { outArray[j++] = el; } } return outArray; } function addCSS(css) { var head, styleLink; head = document.getElementsByTagName('head')[0]; if (!head) { return; } styleLink = document.createElement('link'); styleLink.setAttribute('rel','stylesheet'); styleLink.setAttribute('type','text/css'); styleLink.setAttribute('href','data:text/css,'+escape(css)); head.appendChild(styleLink); } function gs(s){ s = s.toLowerCase( ); if (s=="h2") return "\u00a0 \u00a0 " else if (s=="h3") return "\u00a0 \u00a0 \u00a0 \u00a0 " else if (s=="h4") return "\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 "; return ""; } function getInnerText(el) { var s=''; for (var i=0,node; node=el.childNodes[i]; i++) { if (node.nodeType == 1) s += getInnerText(node); else if (node.nodeType == 3) s += node.nodeValue; } return s; } f( ); 

8.6.2. Running the Hack

After installing the user script (Tools Install This User Script), go to http://whatwg.org/specs/web-apps/current-work/. At the bottom of the browser window is a drop-down box labeled Table of Contents. Open the menu to see an outline of all the headers on the page, as shown in Figure 8-6.

Figure 8-6. Table of contents


You can select any of the headings in the menu to jump to that section on the page.

     < Day Day Up > 


    Greasemonkey Hacks
    Greasemonkey Hacks: Tips & Tools for Remixing the Web with Firefox
    ISBN: 0596101651
    EAN: 2147483647
    Year: 2005
    Pages: 168
    Authors: Mark Pilgrim

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net