Demo
When to use it
- Long tutorials and documentation-style posts, where readers jump to the step they're stuck on.
- Buyer's guides and roundups, so readers can go straight to the product or section they came for.
- Reference posts readers come back to, such as a glossary or a list of settings, to look up one part.
When not to: If your theme has one built in, as many of ours do, use the theme's, so the post doesn't get two.
The code
.bt-toc,
.bt-toc-target {
--bt-toc-top: 5rem;
}
.bt-toc {
--bt-toc-width: 300px;
--bt-toc-bg: #fff;
--bt-toc-color: #222;
--bt-toc-accent: var(--ghost-accent-color, #4433ff);
position: fixed;
top: var(--bt-toc-top);
right: 1rem;
z-index: 100;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 8px;
font-size: 0.875rem;
line-height: 1.4;
}
.bt-toc-target {
scroll-margin-top: var(--bt-toc-top);
}
.bt-toc-toggle {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0;
padding: 8px 14px;
border: 1px solid rgb(0 0 0 / 0.12);
border-radius: 999px;
background: var(--bt-toc-bg);
color: var(--bt-toc-color);
font: inherit;
font-weight: 600;
cursor: pointer;
box-shadow: 0 2px 10px rgb(0 0 0 / 0.08);
}
.bt-toc-toggle svg {
flex: none;
width: 18px;
height: 18px;
}
.bt-toc-toggle[aria-expanded="true"] .bt-toc-icon-open,
.bt-toc-toggle[aria-expanded="false"] .bt-toc-icon-close {
display: none;
}
.bt-toc-panel {
box-sizing: border-box;
width: min(var(--bt-toc-width), calc(100vw - 2rem));
max-height: calc(100vh - var(--bt-toc-top) - 5rem);
overflow-y: auto;
padding: 12px 8px;
border: 1px solid rgb(0 0 0 / 0.12);
border-radius: 8px;
background: var(--bt-toc-bg);
color: var(--bt-toc-color);
box-shadow: 0 4px 20px rgb(0 0 0 / 0.08);
}
.bt-toc-panel[hidden] {
display: none;
}
.bt-toc-list {
margin: 0;
padding: 0;
list-style: none;
}
.bt-toc-list li {
margin: 0;
padding: 0;
}
.bt-toc-link {
display: block;
padding: 4px 8px 4px 12px;
border-left: 3px solid transparent;
color: inherit;
text-decoration: none;
}
.bt-toc-item-h3 .bt-toc-link {
padding-left: 24px;
}
.bt-toc-link:hover {
text-decoration: underline;
}
.bt-toc-link[aria-current="true"] {
border-left-color: var(--bt-toc-accent);
font-weight: 600;
}
.bt-toc-toggle:focus-visible,
.bt-toc-link:focus-visible {
outline: 2px solid var(--bt-toc-accent);
outline-offset: 2px;
}
@media print {
.bt-toc {
display: none;
}
}(() => {
// Where the post's text is: the class differs between themes.
const CONTENT = '.gh-content, .post-content, .ghost-content';
const HEADINGS = 'h2, h3';
const MIN_HEADINGS = 2;
function slug(text) {
return text.toLowerCase().trim().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '') || 'section';
}
function init() {
const content = document.querySelector(CONTENT);
if (!content || document.querySelector('.bt-toc')) return;
const headings = [...content.querySelectorAll(HEADINGS)].filter((h) => h.textContent.trim());
if (headings.length < MIN_HEADINGS) return;
const toc = document.createElement('div');
toc.className = 'bt-toc';
toc.innerHTML = `
<button class="bt-toc-toggle" type="button" aria-expanded="false" aria-controls="bt-toc-panel">
<svg class="bt-toc-icon-open" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" focusable="false"><path d="M4 6h16M7 12h13M10 18h10"/></svg>
<svg class="bt-toc-icon-close" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" focusable="false"><path d="M18 6 6 18M6 6l12 12"/></svg>
Contents
</button>
<nav class="bt-toc-panel" id="bt-toc-panel" aria-label="Table of contents" hidden>
<ol class="bt-toc-list"></ol>
</nav>`;
const toggle = toc.querySelector('.bt-toc-toggle');
const panel = toc.querySelector('.bt-toc-panel');
const list = toc.querySelector('.bt-toc-list');
const links = headings.map((heading) => {
if (!heading.id) {
let id = slug(heading.textContent);
for (let n = 2; document.getElementById(id); n++) id = `${slug(heading.textContent)}-${n}`;
heading.id = id;
}
heading.classList.add('bt-toc-target');
const item = document.createElement('li');
item.className = `bt-toc-item-${heading.tagName.toLowerCase()}`;
const link = document.createElement('a');
link.className = 'bt-toc-link';
link.href = `#${encodeURIComponent(heading.id)}`;
link.textContent = heading.textContent.trim();
item.append(link);
list.append(item);
return link;
});
const setOpen = (open) => {
toggle.setAttribute('aria-expanded', String(open));
panel.hidden = !open;
};
toggle.addEventListener('click', () => setOpen(panel.hidden));
// On a phone the open panel covers the text: close it once a heading is chosen.
list.addEventListener('click', (event) => {
if (event.target.closest('a') && matchMedia('(max-width: 40em)').matches) setOpen(false);
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !panel.hidden) {
setOpen(false);
toggle.focus();
}
});
document.addEventListener('click', (event) => {
if (!panel.hidden && !toc.contains(event.target)) setOpen(false);
});
// Mark the last heading that has scrolled past the top of the window, or the last one
// at the end of the page, where a short last section can't reach the top.
const root = document.scrollingElement || document.documentElement;
let ticking = false;
const update = () => {
ticking = false;
const offset = parseFloat(getComputedStyle(headings[0]).scrollMarginTop) + 10;
let current = -1;
headings.forEach((heading, i) => {
if (heading.getBoundingClientRect().top <= offset) current = i;
});
if (window.scrollY > 0 && window.scrollY + window.innerHeight >= root.scrollHeight - 2) current = headings.length - 1;
links.forEach((link, i) => {
if (i === current) link.setAttribute('aria-current', 'true');
else link.removeAttribute('aria-current');
});
};
const request = () => {
if (!ticking) {
ticking = true;
requestAnimationFrame(update);
}
};
addEventListener('scroll', request, { passive: true });
addEventListener('resize', request);
document.body.append(toc);
update();
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();Add it to your site
- Copy the CSS and paste it in Settings › Advanced › Code injection › Site headerSettings › Advanced › Code injection › Site header (opens your Ghost Admin in a new tab), between
<style>and</style>. Once per site. - Copy the JS and paste it in Settings › Advanced › Code injection › Site footerSettings › Advanced › Code injection › Site footer (opens your Ghost Admin in a new tab), between
<script>and</script>. Save. - Open any post on your site to see it: it works on every post, with nothing to add to them.
How it works
The script collects the H2 and H3 headings of your post and builds a list of links to them. It adds a Contents button to the top right of the window; choosing it opens the list, and choosing it again, pressing Esc or choosing anywhere else closes it. As the reader scrolls, the section they’re in is marked with a bar and bold text, and screen readers hear it as the current one.
Ghost already gives every heading an ID, so the links work without editing your posts. Posts with fewer than two headings get no table of contents, and pages without post text are left alone. There’s no library to load.
Things to know
- Your theme’s content class: the script looks for
.gh-content,.post-contentor.ghost-content, which covers most Ghost themes. If yours uses another class, add it to theCONTENTline at the top of the script. - Only on some posts: to show it on some posts only, put the CSS and the script in each post’s Post settings › Code injection instead of the site-wide one.
- Dark themes: set
--bt-toc-bgand--bt-toc-colorto your theme’s colors.
Ghost has no table of contents of its own, but some themes include one, as many of ours do. Check your theme’s settings before adding this. For more on code injection, see Ghost code injection.
Customize
| Variable | Default | What it changes |
|---|---|---|
--bt-toc-top | 5rem | The distance from the top of the window to the button, and the space kept above a heading after a jump, so a sticky header doesn't cover it. |
--bt-toc-width | 300px | The width of the open list. |
--bt-toc-bg | #fff | The background of the button and the list. |
--bt-toc-color | #222 | The text color of the button and the list. |
--bt-toc-accent | var(--ghost-accent-color, #4433ff) | The bar beside the current section and the focus ring. Defaults to your site's accent color. |