Content & Media

Free Table of Contents Widget

Auto-build a linked table of contents from the headings on your page.

Table of Contents scans the h2 and h3 headings inside your article and renders a clean anchor jump list that highlights the current section as visitors scroll. It is built for blogs, documentation, and long-form pages that want better navigation without a plugin. Paste one script tag where the list should appear — it finds your headings, adds anchors, and keeps everything in sync automatically.

Live demo

Embed this widget

Paste either snippet into your page — a Custom HTML block on WordPress, Shopify, or Squarespace works too. Both snippets update live as you customize, so what you copy is exactly what you configured.

Hosted (recommended)html
<script src="https://hayneslab.dev/widgets/table-of-contents.js" async></script>
<!-- Free Table of Contents widget by haynes lab — https://hayneslab.dev/tools/widgets/table-of-contents -->
Inline (self-contained)html
<!-- Free Table of Contents widget by haynes lab — https://hayneslab.dev/tools/widgets/table-of-contents -->
<script>
/*!
 * haynes lab — Table of Contents widget (free)
 * Docs & embed code: https://hayneslab.dev/tools/widgets/table-of-contents
 */
(function () {
  'use strict';

  var PREFIX = 'hlw-table-of-contents';
  var STYLE_ID = 'hlw-table-of-contents-styles';

  function findScript() {
    return document.currentScript ||
      document.querySelector('script[src*="widgets/table-of-contents.js"]');
  }

  function injectStyles() {
    if (document.getElementById(STYLE_ID)) return;
    var css =
      '.' + PREFIX + ', .' + PREFIX + ' * { box-sizing: border-box; }' +
      '.' + PREFIX + ' { position: relative; max-width: 720px; margin: 0 auto; padding: 20px 24px 26px;' +
      ' font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;' +
      ' font-size: 15px; line-height: 1.5; color: #1f2937; background: #ffffff;' +
      ' border: 1px solid #e5e7eb; border-radius: 12px; }' +
      '.' + PREFIX + '__title { margin: 0 0 10px; font-size: 13px; font-weight: 700;' +
      ' text-transform: uppercase; letter-spacing: 0.06em; color: #6b7280; }' +
      '.' + PREFIX + '__list { list-style: none; margin: 0; padding: 0; }' +
      '.' + PREFIX + '__item { margin: 0; }' +
      '.' + PREFIX + '__item--h3 { padding-left: 18px; }' +
      '.' + PREFIX + '__link { display: block; padding: 5px 10px; border-left: 2px solid #e5e7eb;' +
      ' color: #4b5563; text-decoration: none; border-radius: 0 6px 6px 0; }' +
      '.' + PREFIX + '__item--h3 .' + PREFIX + '__link { font-size: 14px; }' +
      '.' + PREFIX + '__link:hover { color: var(--hlw-accent); background: #f9fafb; }' +
      '.' + PREFIX + '__link:focus-visible { outline: 2px solid var(--hlw-accent); outline-offset: 2px; }' +
      '.' + PREFIX + '__link[aria-current="true"] { border-left-color: var(--hlw-accent);' +
      ' color: var(--hlw-accent); font-weight: 600; background: #f9fafb; }' +
      '.' + PREFIX + '__credit { position: absolute; right: 10px; bottom: 6px; font-size: 11px;' +
      ' display: inline-flex; align-items: center; gap: 4px; color: #9ca3af; text-decoration: none; }' +
      '.' + PREFIX + '__credit svg { display: block; }' +
      '.' + PREFIX + '__credit:hover { color: #6b7280; text-decoration: underline; }';
    var style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = css;
    document.head.appendChild(style);
  }

  function el(tag, className, text) {
    var node = document.createElement(tag);
    if (className) node.className = className;
    if (text != null) node.textContent = text;
    return node;
  }

  function logoSvg() {
    var svgNS = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(svgNS, 'svg');
    svg.setAttribute('viewBox', '0 0 32 32');
    svg.setAttribute('width', '13');
    svg.setAttribute('height', '13');
    svg.setAttribute('aria-hidden', 'true');
    svg.setAttribute('focusable', 'false');
    function circle(cx, cy, r, attrs) {
      var c = document.createElementNS(svgNS, 'circle');
      c.setAttribute('cx', cx);
      c.setAttribute('cy', cy);
      c.setAttribute('r', r);
      for (var key in attrs) c.setAttribute(key, attrs[key]);
      svg.appendChild(c);
    }
    circle(16, 16, 16, { fill: '#0f0a0a' });
    circle(16, 16, 12, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1, opacity: 0.3 });
    circle(16, 16, 9, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1, opacity: 0.5 });
    circle(16, 16, 6, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1.2, opacity: 0.9 });
    circle(16, 16, 3, { fill: '#06b6d4' });
    circle(24.5, 7.5, 2, { fill: '#f97316' });
    circle(7, 16, 1.8, { fill: '#f97316' });
    circle(20, 20, 1.5, { fill: '#f97316' });
    return svg;
  }

  function findContainer(script) {
    var target = script.getAttribute('data-hl-target') || 'article, main';
    var container = null;
    try {
      container = document.querySelector(target);
    } catch (e) {
      console.warn('[haynes lab table-of-contents] data-hl-target is not a valid selector: "' + target + '".', e);
    }
    if (!container) {
      container = script.closest('.widget-demo__stage') || document.body;
    }
    return container;
  }

  function headingId(heading, text) {
    if (heading.id) return heading.id;
    var base = String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'section';
    var id = base;
    var n = 1;
    while (document.getElementById(id)) {
      id = base + '-' + (++n);
    }
    heading.id = id;
    return id;
  }

  function build(script) {
    var container = findContainer(script);
    var headings = container.querySelectorAll('h2, h3');
    if (!headings.length) {
      console.warn('[haynes lab table-of-contents] No h2/h3 headings found inside the target. Nothing rendered.');
      return;
    }

    var title = script.getAttribute('data-hl-title') || 'On this page';
    var accent = script.getAttribute('data-hl-accent') || '#f97316';

    injectStyles();

    var root = el('nav', PREFIX);
    root.setAttribute('aria-label', title);
    root.style.setProperty('--hlw-accent', accent);

    root.appendChild(el('p', PREFIX + '__title', title));

    var list = el('ul', PREFIX + '__list');
    var entries = [];

    Array.prototype.forEach.call(headings, function (heading) {
      var text = heading.textContent.trim();
      if (!text) return;
      var id = headingId(heading, text);
      if (!heading.style.scrollMarginTop) heading.style.scrollMarginTop = '80px';

      var isH3 = heading.nodeName === 'H3';
      var item = el('li', PREFIX + '__item' + (isH3 ? ' ' + PREFIX + '__item--h3' : ''));
      var link = el('a', PREFIX + '__link', text);
      link.href = '#' + id;
      link.setAttribute('aria-current', 'false');
      item.appendChild(link);
      list.appendChild(item);
      entries.push({ heading: heading, link: link });
    });

    if (!entries.length) {
      console.warn('[haynes lab table-of-contents] Headings found but all were empty. Nothing rendered.');
      return;
    }
    root.appendChild(list);

    var ticking = false;
    function updateActive() {
      ticking = false;
      var current = 0;
      var top = window.pageYOffset + 96;
      for (var i = 0; i < entries.length; i++) {
        if (entries[i].heading.getBoundingClientRect().top + window.pageYOffset <= top) current = i;
      }
      entries.forEach(function (entry, i) {
        entry.link.setAttribute('aria-current', i === current ? 'true' : 'false');
      });
    }
    function onScroll() {
      if (!ticking) {
        ticking = true;
        window.requestAnimationFrame(updateActive);
      }
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });
    updateActive();

    var credit = el('a', PREFIX + '__credit');
    credit.appendChild(logoSvg());
    credit.appendChild(document.createTextNode('Powered by haynes lab'));
    credit.href = 'https://hayneslab.dev/tools/widgets/table-of-contents';
    credit.target = '_blank';
    credit.rel = 'noopener';
    root.appendChild(credit);

    if (script.parentNode && script.parentNode.nodeName !== 'HEAD') {
      script.insertAdjacentElement('afterend', root);
    } else {
      document.body.appendChild(root);
    }
  }

  function init() {
    var script = findScript();
    if (!script) {
      console.warn('[haynes lab table-of-contents] Could not locate its own script tag. Nothing rendered.');
      return;
    }
    build(script);
  }

  if (document.body) {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();

</script>

Configuration

Every option is an attribute on the script tag — the same attributes the customizer above exposes. All attributes are optional unless marked required — defaults apply when omitted.

AttributeDefaultDescription
data-hl-target"article, main"CSS selector for the container to scan for h2/h3 headings; falls back to the page body when no match is found.
data-hl-title"On this page"Heading shown above the list of links.
data-hl-accent"#f97316"CSS color used for the active link and hover state.

Frequently asked questions

How do I install the table of contents?

Paste the script tag where you want the list to appear — usually right before your article content. It renders inline at that spot, scans your page for h2/h3 headings, and builds the jump links automatically.

Can I change which content gets scanned or how it looks?

Yes. Set data-hl-target to any CSS selector (default is "article, main") to choose which part of the page is scanned for headings, use data-hl-title for the label above the list, and data-hl-accent to match the active-link color to your brand.

Does it work on WordPress, Shopify, or Squarespace?

Yes — it is a single vanilla JS file with no dependencies, so it works anywhere you can paste a script tag, including WordPress, Shopify, Squarespace, and plain HTML sites.

More free widgets

Need a custom widget?

We build custom widgets, integrations, and whole products. Tell us what your site needs and we'll scope it.

Get in Touch