← All examples

JavaScript Navigation

Table of contents from headings

Builds a floating table of contents from H2 and H3 headings with links to each section.

Code to copy

var heads = document.querySelectorAll('h2, h3');
if (heads.length) {
  var box = document.createElement('nav');
  box.style.cssText = 'position:fixed;top:60px;right:10px;max-height:70vh;overflow:auto;background:#fff;color:#111;border:1px solid #ccc;padding:8px 12px;font:13px sans-serif;z-index:99999;max-width:240px';
  heads.forEach(function (h, i) {
    if (!h.id) { h.id = 'nv-toc-' + i; }
    var a = document.createElement('a');
    a.href = '#' + h.id;
    a.textContent = h.textContent.trim();
    a.style.cssText = 'display:block;padding:2px 0;color:#006870;text-decoration:none;' + (h.tagName === 'H3' ? 'margin-left:12px' : '');
    box.appendChild(a);
  });
  document.body.appendChild(box);
}

How to use this example

  1. Copy the code with the button above.
  2. Install JustZix (2 minutes) and open the extension on the target page.
  3. Add a new rule matching that page.
  4. Paste the code into the rule's JavaScript panel and save — it runs on every page visit.

Rate this example

No ratings yet — be the first.

Does this example work?

Snippets are useless without somewhere to paste them.

JustZix takes 2 minutes to install and runs your code on every matching page. No account, no payment.

Download free See use cases