Automatic Anchor Links from Headers
Description: This jQuery script automatically generates a table of contents from all of the headers on the page (H1, H2, CUSTOM etc), enabling viewers to navigate to key sections of with ease. An HTML anchor is dynamically inserted into each header, making it navigable. The script supports the following customizations:
- Specify the header elements the script should parse to create the TOC (defaults to "H1", "H2", "H3", and ".customheader" class).
- Define whether to animate the scroll to header mechanic.
- Define the maximum number of characters the script should extract from each header to create each TOC link.
- Create and position an empty DIV container anywhere on the page to display the TOC.
The TOC container can be made "sticky" with additional changes, so it always appear in view. See the section "Making the Table of Contents Sticky" by the author below.
See also: jQuery Scroll to Top Control and Scrolling HTML Bookmarks
Demo:
Installation Directions
Insert the following script in the HEAD section of your page:
And download the following .js file: jqueryheaderanchors.js
Then, define an empty DIV to house the generated Table of
Contents. By default the DIV should have an ID of "tocbox
":
<div id="tocbox"></div>
Inside the jqueryheaderanchors.js, you can modify various settings of the script:
var targetels= ['h1', 'h2', 'h3', '.customheader'] var outputdivid = 'tocbox' // id of empty element to house TOC links var headerlength = 70 // max length of each header link var trailingmark = '...' // trailing text to add to each of header link if necessary var animated = true // animate scrolling? var uloutput = '<ul class="tableofcontents">\n' // UL and classname to use for the generated TOC container
Making the Table of Contents Sticky (Author Notes)
The generated Table of Contents can be made sticky in a variety of ways:
-
Add
position:fixed
orposition:sticky
to the TOC container (More Info) -
Use a script like Sticky Content script from DD
-
For Wordpress Users, use the plugin Q2W3 Fixed Widget