When an article is short, it usually does not need a table of contents.
But once a post grows to 10–15 screens of content, finding a specific section becomes much harder. This is especially noticeable in technical articles, where readers often do not need the entire post — they need one particular part:
-
installation;
-
configuration;
-
error resolution;
-
code examples;
-
testing;
-
the final working implementation.
For this kind of article, a table of contents is very useful:
Table of Contents
Why the problem appeared
How the solution works
How anchors are created
How the menu is built
How to highlight the current section
Full code
Of course, you can write it manually:
<nav>
<a href="/blog/my-article#problem">
Why the problem appeared
</a>
<a href="/blog/my-article#solution">
How the solution works
</a>
<a href="/blog/my-article#code">
Full code
</a>
</nav>
and then manually assign matching IDs:
<h2 id="problem">
Why the problem appeared
</h2>
<h2 id="solution">
How the solution works
</h2>
<h2 id="code">
Full code
</h2>
For one article, that is not difficult.
The problem starts when you have many of them.
Why a Manual Table of Contents Quickly Becomes Inconvenient
Imagine the article is already published, but several weeks later you add a new section:
<h2>How to Test the Result</h2>
Now you need to remember to:
-
create an
id; -
add a link to the table of contents;
-
place it in the correct position;
-
verify that the anchor works;
-
update the table of contents again if the heading changes later.
If you have dozens or hundreds of articles, maintaining this manually becomes tedious.
The interesting part is that the structure already exists in the HTML.
For example:
<h2>Why the problem appeared</h2>
<h2>How the solution works</h2>
<h3>How anchors are created</h3>
<h3>How the menu is built</h3>
<h2>Full code</h2>
The browser already has all the information required to build the table of contents.
We only need to collect it automatically.
What We Decided to Build
The logic is fairly simple:
page loads
↓
find the article container
↓
find H2 and H3 headings
↓
assign unique IDs
↓
create links
↓
build a nested table of contents
↓
scroll to the selected heading
↓
highlight the current section
As a result, the article author does not need to manage the table of contents at all.
They simply write the article:
<h2>Installation</h2>
<p>...</p>
<h2>Configuration</h2>
<p>...</p>
<h3>Cache Configuration</h3>
<p>...</p>
and the table of contents is generated automatically.
Why We Use H2 and H3 but Not H1
A normal article page should already have one main heading:
<h1>
How to Automatically Generate a Table of Contents
</h1>
That is the title of the page itself.
There is usually little value in adding it to the table of contents again.
The main article sections should be marked up with:
<h2>
and subsections with:
<h3>
So the JavaScript searches for:
article.querySelectorAll('h2, h3');
This gives us a natural document hierarchy:
H1 — article title
H2 — section
H3 — subsection
H3 — subsection
H2 — next section
The table of contents is therefore generated directly from the semantic structure of the page.
Every Heading Needs an Anchor
To navigate to a specific part of the page, the heading needs an id.
For example:
<h2 id="how-it-works">
How It Works
</h2>
Then we can create a link to that section.
But manually adding IDs to every heading is exactly what we want to avoid.
So JavaScript generates them automatically.
Creating IDs from Heading Text
Suppose the article contains:
<h2>How It Works</h2>
From the text:
How It Works
we generate:
how-it-works
and assign:
<h2 id="how-it-works">
How It Works
</h2>
The function can look like this:
function slugify(text) {
return text
.toLowerCase()
.trim()
.normalize('NFKC')
.replace(/[^\p{L}\p{N}]+/gu, '-')
.replace(/^-+|-+$/g, '');
}
It:
-
converts the text to lowercase;
-
trims unnecessary whitespace;
-
replaces groups of special characters with
-; -
removes hyphens from the beginning and end.
For example:
How Does MODX + Fenom Work?
becomes:
how-does-modx-fenom-work
The same function also supports Unicode, so it works with Cyrillic and other alphabets if needed.
What If Two Headings Have the Same Text?
An article can easily contain two identical headings:
<h2>Example</h2>
...
<h2>Example</h2>
Both cannot have:
id="example"
because IDs should be unique on the page.
So we generate:
example
example-2
example-3
and so on.
To do that, we only need to keep track of IDs that have already been used.
Existing IDs Should Not Be Overwritten
Sometimes an author has already intentionally written:
<h2 id="installation">
Installation
</h2>
That ID should remain unchanged.
It may already be used by:
-
external links;
-
documentation;
-
bookmarks;
-
search results;
-
other articles.
So the rule is simple:
heading already has an id
↓
keep it
no id exists
↓
generate one automatically
Building the H2 → H3 Structure
We could simply output every heading as a flat list:
Installation
Configuration
Cache Configuration
Database Configuration
Testing
But that loses the structure of the article.
This is much clearer:
Installation
Configuration
Cache Configuration
Database Configuration
Testing
So each H2 becomes a main item, while the following H3 headings become nested items.
For example:
<h2>Configuration</h2>
<h3>Cache Configuration</h3>
<h3>Database Configuration</h3>
becomes approximately:
<ul>
<li>
<a href="...">
Configuration
</a>
<ul>
<li>
<a href="...">
Cache Configuration
</a>
</li>
<li>
<a href="...">
Database Configuration
</a>
</li>
</ul>
</li>
</ul>
This gives us a properly structured semantic table of contents.
An Important Problem: <base> Breaks Normal href="#section" Links
This is where we encountered a subtle issue that is easy to overlook.
Many websites use:
<base href="https://example.com/">
inside <head>.
This is also fairly common on MODX websites.
Normally, <base> is useful because relative URLs are resolved against the specified base URL.
But it also affects fragment-only links.
Suppose we create:
<a href="#installation">
Installation
</a>
and the current article is located at:
https://example.com/blog/my-article
You might expect the browser to navigate to:
https://example.com/blog/my-article#installation
But because of <base>, the link may instead be resolved relative to:
https://example.com/
resulting in:
https://example.com/#installation
Instead of scrolling inside the current article, the user may be taken to the homepage.
For an automatic table of contents, this is a serious bug.
Why We Do Not Use a Bare href="#..."
Many table-of-contents examples use:
link.href = '#' + id;
That works perfectly on a site without <base>.
But on a site containing:
<base href="https://example.com/">
it is unreliable.
Instead, we build the link from the current page path:
link.href =
window.location.pathname +
window.location.search +
'#' +
encodeURIComponent(id);
If the article is located at:
/blog/my-article
the result becomes:
/blog/my-article#installation
If the URL has query parameters:
/blog/my-article?lang=en
they are preserved:
/blog/my-article?lang=en#installation
Because the URL starts with /, the <base> element can no longer redirect the link to a different page.
We Also Store the ID in data-target
For JavaScript navigation, we do not need to parse href at all.
So we also store:
link.dataset.target = id;
The generated HTML looks roughly like this:
<a
href="/blog/my-article#installation"
data-target="installation"
>
Installation
</a>
Now:
-
hrefremains a valid working URL; -
<base>does not break it; -
JavaScript gets the raw section ID from
data-target.
This is useful for both smooth scrolling and active-section highlighting.
Why the Link Should Still Work Without JavaScript
We could create:
<a href="javascript:void(0)">
and make the entire table of contents depend on JavaScript.
But that is not a good fallback.
If JavaScript fails to load for any reason, the navigation becomes useless.
Instead, we keep a real URL:
/blog/my-article#installation
This gives us progressive enhancement:
JavaScript works
↓
smooth scrolling + active state
JavaScript fails
↓
regular HTML anchor still works
Smooth Scrolling
When the user clicks a table-of-contents link, we read:
const id = link.dataset.target;
then find the matching heading:
const target = document.getElementById(id);
and scroll to it:
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
This way, our navigation does not depend on how the browser resolves href.
Updating the URL After Scrolling
If we only call:
scrollIntoView()
the user reaches the correct section, but the URL does not change.
It is useful to have:
/blog/my-article#installation
in the address bar because that URL can be:
-
copied;
-
shared;
-
bookmarked;
-
opened directly later.
So after scrolling, we update the URL:
history.pushState(
null,
'',
window.location.pathname +
window.location.search +
'#' +
encodeURIComponent(id)
);
The page itself does not reload.
Handling a Fixed Header
Anchor navigation has another common issue.
If the site has a fixed header:
position: fixed;
the heading may end up hidden underneath it after navigation.
The solution is simple:
.article-content h2,
.article-content h3 {
scroll-margin-top: 100px;
}
Now the browser leaves some space above the heading.
The exact value:
100px
should be adjusted to match the actual header height.
Hide the Table of Contents for Short Articles
A short article with only one or two sections may not need a table of contents at all.
So we define a minimum heading count:
const MIN_HEADINGS = 3;
and check:
if (headings.length < MIN_HEADINGS) {
return;
}
On shorter posts, the table of contents simply remains hidden.
Highlighting the Section the Reader Is Currently Viewing
The table of contents becomes more useful if the active section is highlighted:
Installation
● Configuration
Cache Configuration
Database Configuration
Testing
The logic is straightforward.
We take the current scroll position:
const scrollPosition =
window.scrollY + 140;
then find the last heading that has already passed that point.
After that, we compare:
link.dataset.target
with:
currentHeading.id
and add the:
active
class to the matching link.
Notice that we do not compare href values here either.
So <base> does not affect scrollspy logic at all.
Why We Do Not Run Heavy Logic on Every scroll Event
The:
scroll
event can fire very frequently.
For a small article that is not a major performance problem, but there is no reason to repeat the same DOM calculations multiple times per frame.
So we use:
requestAnimationFrame()
together with:
let ticking = false;
This limits the update to roughly one execution per animation frame.
How It Looks on Desktop
On wide screens, the table of contents can sit next to the article:
┌──────────────────┬─────────────────────────────┐
│ Table of Contents│ │
│ │ Article content │
│ Section 1 │ │
│ Section 2 │ H2 Heading │
│ Subsection │ │
│ Section 3 │ text... │
│ │ │
└──────────────────┴─────────────────────────────┘
and use:
position: sticky;
top: 100px;
so it stays visible while the reader scrolls.
How It Works on Mobile
A permanent sidebar takes too much space on small screens.
So with a media query, the layout becomes a single column:
┌─────────────────────────────┐
│ Table of Contents │
│ │
│ Section 1 │
│ Section 2 │
│ Section 3 │
├─────────────────────────────┤
│ │
│ Article │
│ │
└─────────────────────────────┘
No separate mobile JavaScript is needed.
A Special Case for Technical Blogs Using MODX + Fenom
In our case, technical articles often contain examples of Fenom itself:
{if $author}
JSON:
{"strip": true}
PHP:
if ($result) {
return $result;
}
If the resource content is parsed by Fenom again, the template engine may try to execute those examples.
So the article content is output like this:
{ignore}
[[*content]]
{/ignore}
For example:
<article
class="article-content js-article-content"
id="article-content"
>
{ignore}
[[*content]]
{/ignore}
</article>
This allows JSON, JavaScript, PHP, and Fenom examples to remain ordinary article content instead of being interpreted as template syntax.
What the Article Author Has to Do
After installing the system, the article author no longer needs to think about the table of contents.
They only need to use headings correctly:
<h2>Why the problem appeared</h2>
<p>...</p>
<h2>How to solve it</h2>
<p>...</p>
<h3>First option</h3>
<p>...</p>
<h3>Second option</h3>
<p>...</p>
<h2>Full code</h2>
After the page loads, JavaScript automatically:
finds H2/H3
↓
creates unique IDs
↓
builds H2 → H3 hierarchy
↓
creates links using the current page URL
↓
avoids problems caused by <base>
↓
enables smooth scrolling
↓
updates the URL hash
↓
highlights the active section
The article structure itself becomes the single source of truth for the table of contents.
Full Code
Below is the complete implementation without jQuery or any third-party libraries.
HTML / Fenom Template
<section class="o-container u-padding -medium-bottom">
<div class="article-layout">
<aside class="article-sidebar">
<nav
class="article-toc js-article-toc"
aria-label="Table of contents"
hidden
>
<div class="article-toc__title">
Table of Contents
</div>
<ul
class="article-toc__list js-article-toc-list"
></ul>
</nav>
</aside>
<article
class="article-content js-article-content"
id="article-content"
>
{ignore}
[[*content]]
{/ignore}
</article>
</div>
</section>
CSS
html {
scroll-behavior: smooth;
}
/* ==========================
Article layout
========================== */
.article-layout {
display: grid;
grid-template-columns:
minmax(200px, 260px)
minmax(0, 1fr);
gap: 50px;
align-items: start;
}
/* ==========================
Table of contents
========================== */
.article-toc {
position: sticky;
top: 100px;
padding: 20px;
border: 1px solid #e7e7e7;
border-radius: 8px;
}
.article-toc__title {
margin-bottom: 15px;
font-size: 18px;
font-weight: 600;
}
.article-toc__list,
.article-toc__sublist {
margin: 0;
padding: 0;
list-style: none;
}
.article-toc__sublist {
margin-top: 7px;
padding-left: 15px;
}
.article-toc__item {
margin: 7px 0;
}
.article-toc__link {
display: block;
font-size: 14px;
line-height: 1.4;
text-decoration: none;
opacity: 0.7;
transition:
opacity 0.2s ease,
transform 0.2s ease;
}
.article-toc__link:hover,
.article-toc__link.active {
opacity: 1;
}
.article-toc__link.active {
font-weight: 600;
transform: translateX(3px);
}
/* ==========================
Anchor offset
========================== */
.article-content h2,
.article-content h3 {
scroll-margin-top: 100px;
}
/* ==========================
Mobile
========================== */
@media (max-width: 900px) {
.article-layout {
grid-template-columns: 1fr;
gap: 30px;
}
.article-toc {
position: static;
}
}
JavaScript
document.addEventListener(
'DOMContentLoaded',
function () {
const article =
document.querySelector(
'.js-article-content'
);
const toc =
document.querySelector(
'.js-article-toc'
);
const tocList =
document.querySelector(
'.js-article-toc-list'
);
if (
!article ||
!toc ||
!tocList
) {
return;
}
/*
* Main article sections are H2,
* subsections are H3.
*/
const headings = Array.from(
article.querySelectorAll(
'h2, h3'
)
).filter((heading) => {
return (
heading.textContent.trim()
!== ''
);
});
/*
* Do not show the TOC
* for very short articles.
*/
const MIN_HEADINGS = 3;
if (
headings.length
< MIN_HEADINGS
) {
return;
}
/*
* Create a slug from heading text.
*
* Supports Unicode,
* so it also works with Cyrillic
* and other alphabets.
*/
function slugify(text) {
return text
.toLowerCase()
.trim()
.normalize('NFKC')
.replace(
/[^\p{L}\p{N}]+/gu,
'-'
)
.replace(
/^-+|-+$/g,
''
);
}
/*
* IDs that have already been used.
*/
const usedIds = new Set();
/*
* First preserve IDs
* that were manually assigned.
*/
headings.forEach(
(heading) => {
if (heading.id) {
usedIds.add(
heading.id
);
}
}
);
/*
* Create a unique ID
* only when one does not exist.
*/
function createUniqueId(
heading,
index
) {
if (heading.id) {
return heading.id;
}
let base = slugify(
heading.textContent
);
if (!base) {
base =
'section-'
+ (index + 1);
}
let id = base;
let counter = 2;
while (
usedIds.has(id)
) {
id =
base
+ '-'
+ counter;
counter++;
}
usedIds.add(id);
heading.id = id;
return id;
}
/*
* Create a link.
*
* IMPORTANT:
*
* We do not use:
*
* href="#section"
*
* because when the page contains:
*
* <base href="...">
*
* the browser may resolve the fragment
* relative to the base URL.
*
* Instead, explicitly use
* the current pathname + query string.
*/
function createLink(
heading,
index
) {
const id =
createUniqueId(
heading,
index
);
const link =
document.createElement(
'a'
);
link.className =
'article-toc__link';
link.href =
window.location.pathname
+ window.location.search
+ '#'
+ encodeURIComponent(id);
/*
* For JavaScript navigation
* we use the raw ID
* instead of parsing href.
*/
link.dataset.target = id;
link.textContent =
heading.textContent.trim();
return link;
}
/*
* Build:
*
* H2
* H3
* H3
* H2
*/
let currentH2Item = null;
headings.forEach(
(heading, index) => {
const item =
document.createElement(
'li'
);
item.className =
'article-toc__item';
const link =
createLink(
heading,
index
);
item.appendChild(link);
/*
* H2 — main section.
*/
if (
heading.tagName
.toLowerCase()
=== 'h2'
) {
tocList.appendChild(
item
);
currentH2Item =
item;
return;
}
/*
* H3 — subsection.
*/
if (
heading.tagName
.toLowerCase()
=== 'h3'
) {
/*
* If an H3 appears
* before the first H2,
* add it as a normal item.
*/
if (
!currentH2Item
) {
tocList
.appendChild(
item
);
return;
}
let sublist =
currentH2Item
.querySelector(
':scope > '
+ '.article-toc__sublist'
);
if (!sublist) {
sublist =
document
.createElement(
'ul'
);
sublist.className =
'article-toc__sublist';
currentH2Item
.appendChild(
sublist
);
}
sublist.appendChild(
item
);
}
}
);
/*
* The TOC was built successfully,
* so now we can display it.
*/
toc.hidden = false;
const links = Array.from(
toc.querySelectorAll(
'.article-toc__link'
)
);
/*
* =================================
* Click navigation
* =================================
*
* We do not rely on the browser's
* default href resolution.
*
* Therefore <base> no longer
* causes problems.
*/
toc.addEventListener(
'click',
function (event) {
const link =
event.target.closest(
'.article-toc__link'
);
if (!link) {
return;
}
const id =
link.dataset.target;
if (!id) {
return;
}
const target =
document.getElementById(
id
);
if (!target) {
return;
}
event.preventDefault();
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
/*
* Update the URL
* without reloading the page.
*/
history.pushState(
null,
'',
window.location.pathname
+ window.location.search
+ '#'
+ encodeURIComponent(id)
);
}
);
/*
* =================================
* Highlight the current section
* =================================
*/
function updateActiveLink() {
const scrollPosition =
window.scrollY + 140;
let currentHeading =
headings[0];
headings.forEach(
(heading) => {
if (
heading.offsetTop
<= scrollPosition
) {
currentHeading =
heading;
}
}
);
links.forEach(
(link) => {
const isActive =
link.dataset.target
=== currentHeading.id;
link.classList.toggle(
'active',
isActive
);
}
);
}
/*
* Limit the number of calculations
* during scrolling.
*/
let ticking = false;
window.addEventListener(
'scroll',
function () {
if (ticking) {
return;
}
ticking = true;
requestAnimationFrame(
function () {
updateActiveLink();
ticking = false;
}
);
},
{
passive: true
}
);
/*
* Initial state.
*/
updateActiveLink();
}
);
What We Ended Up With
After this improvement, the article itself becomes the source of navigation data:
H2 / H3
↓
automatic unique IDs
↓
table of contents
↓
links to the current page
↓
safe behavior with <base>
↓
smooth scrolling
↓
URL with #section
↓
active-section highlighting
The author no longer needs to manually:
-
create the table of contents;
-
invent anchor IDs;
-
keep heading names and links synchronized;
-
update navigation after editing;
-
account for the presence of
<base>.
Add a new:
<h2>
and a new main item appears automatically.
Add:
<h3>
and a subsection appears.
Change the heading text, and the table of contents updates automatically.
Most importantly, the solution is not tied to MODX. The JavaScript works with the final HTML, so the same approach can be used in WordPress, a static website, or practically any other CMS.
For MODX + Fenom, there is only one additional detail: technical article content is best isolated from the template engine:
{ignore}
[[*content]]
{/ignore}
so JSON, PHP, JavaScript, and Fenom examples inside <code> remain code for the reader instead of being interpreted by the server.
