A table of contents is a list of in-page links that lets readers jump to a specific section and gives them an overview of what the content covers. For long-form text it pays off twice: orientation and navigation. The build described here parses Markdown to HTML, derives a link list from the headings, tracks the section currently being read with the Intersection Observer API, animates link clicks, and uses Vue's <transition-group> to animate the list itself.

From Markdown to HTML

Web text content is frequently authored in Markdown. The parser used here is marked; other parsers work equally well. The source file is fetched from GitHub, and a single call to marked(<markdown>, <options>) converts it. The resulting HTML is then placed into the DOM by replacing the container's content through innerHTML.

async function fetchAndParseMarkdown() {
  const url = 'https://gist.githubusercontent.com/lisilinhart/e9dcf5298adff7c2c2a4da9ce2a3db3f/raw/2f1a0d47eba64756c22460b5d2919d45d8118d42/red_panda.md'
  const response = await fetch(url)
  const data = await response.text()
  const htmlFromMarkdown = marked(data, { sanitize: true });
  return htmlFromMarkdown
}
async function init() {
  const $main = document.querySelector('#app');
  const htmlContent = await fetchAndParseMarkdown();
  $main.innerHTML = htmlContent
}


init();

To collect the headings, querySelectorAll('h1, h2') selects every <h1> and <h2> inside the Markdown container. Each heading contributes three pieces of data: its inner text, its depth (1 or 2), and the element ID used as the link target.

function generateLinkMarkup($contentElement) {
  const headings = [...$contentElement.querySelectorAll('h1, h2')]
  const parsedHeadings = headings.map(heading => {
    return {
      title: heading.innerText,
      depth: heading.nodeName.replace(/\D/g,''),
      id: heading.getAttribute('id')
    }
  })
  console.log(parsedHeadings)
}

The result is an array like this:

[
  {title: "The Red Panda", depth: "1", id: "the-red-panda"},
  {title: "About", depth: "2", id: "about"},
  // ... 
]

ES6 template literals then build the markup. The loop over all headings emits <li> elements, and any entry with depth: 2 also receives the .pl-4 padding class so that <h2> entries appear as indented subheadings. The array of <li> snippets is joined and wrapped in a <ul>.

function generateLinkMarkup($contentElement) {
  // ...
  const htmlMarkup = parsedHeadings.map(h => `
  <li class="${h.depth > 1 ? 'pl-4' : ''}">
    <a href="#${h.id}">${h.title}</a>
  </li>
  `)
  const finalMarkup = `<ul>${htmlMarkup.join('')}</ul>`
  return finalMarkup
}

The finished string is inserted into the DOM.

async function init() {
  const $main = document.querySelector('#content');
  const $aside = document.querySelector('#aside');
  const htmlContent = await fetchAndParseMarkdown();
  $main.innerHTML = htmlContent
  const linkHtml = generateLinkMarkup($main);
  $aside.innerHTML = linkHtml        
}

Tracking the active section

Intersection Observers answer the question of which part of the content is currently being read. MDN's definition:

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

Constructing one via new IntersectionObserver() yields an observer instance. It takes a callback, invoked when an intersection is observed, as its first argument and an options object as its second.

function createObserver() {
  const options = {
    rootMargin: "0px 0px -200px 0px",
    threshold: 1
  }
  const callback = () => { console.log("observed something") }
  return new IntersectionObserver(callback, options)
}

The observer exists but watches nothing yet; the heading elements must each be registered through observe().

const observer = createObserver()
$headings.map(heading => observer.observe(heading))

The link list is handed to the observer as a $links parameter so that the DOM is not re-read on every update. Inside handleObserver, a heading found to intersect the viewport has its id passed to updateLinks, which adjusts the classes on the table of contents entries.

function handleObserver(entries, observer, $links) {
  entries.forEach((entry)=> {
    const { target, isIntersecting, intersectionRatio } = entry
    if (isIntersecting && intersectionRatio >= 1) {
      const visibleId = `#${target.getAttribute('id')}`
      updateLinks(visibleId, $links)
    }
  })
}

That update loops over all links, removes .is-active wherever it exists, and applies it only to the entry that is actually active.

function updateLinks(visibleId, $links) {
  $links.map(link => {
    let href = link.getAttribute('href')
    link.classList.remove('is-active')
    if(href === visibleId) link.classList.add('is-active')
  })
}

At the end of init(), the observer is created, all headings are observed, and the links list is updated so the active entry is highlighted when the observer notices a change.

async function init() {
  // Parsing Markdown
  const $aside = document.querySelector('#aside');


  // Generating a list of heading links
  const $headings = [...$main.querySelectorAll('h1, h2')];


  // Adding an Intersection Observer
  const $links = [...$aside.querySelectorAll('a')]
  const observer = createObserver($links)
  $headings.map(heading => observer.observe(heading))
}

Scrolling with a motion check

Clicking a link should move the reader to the heading with an animation rather than a jump — commonly called smooth scrolling. Because scrolling animations can be harmful to users who prefer reduced motion, the behavior is conditional. window.matchMedia('(prefers-reduced-motion)') reads that preference. Each link gets a click listener, and the heading list $headings together with motionQuery is passed along.

const motionQuery = window.matchMedia('(prefers-reduced-motion)');


$links.map(link => {
  link.addEventListener("click", 
    (evt) => handleLinkClick(evt, $headings, motionQuery)
  )
})

handleLinkClick fires on any link click. It first prevents the default jump, reads the clicked link's href, and locates the heading with the matching id. Setting tabindex to -1 and calling focus() moves focus to that heading so the user knows where they landed. The scroll itself goes through scroll() on window.

When the user prefers reduced motion, the behavior is instant; otherwise it is smooth. The top option adds scroll margin above the heading so it does not sit flush against the top of the window.

function handleLinkClick(evt, $headings, motionQuery) {
  evt.preventDefault()
  let id = evt.target.getAttribute("href").replace('#', '')
  let section = $headings.find(heading => heading.getAttribute('id') === id)
  section.setAttribute('tabindex', -1)
  section.focus()


  window.scroll({
    behavior: motionQuery.matches ? 'instant' : 'smooth',
    top: section.offsetTop - 20
  })
}

Animating list entries with Vue

Vue's <transition-group> is built for list transitions and exposes animation lifecycle hooks with easy access to CSS animations. Vue attaches classes automatically when an element enters (v-enter) or leaves (v-leave) a list, plus v-enter-active and v-leave-active while the animation runs. That matters here because subheadings can animate differently when they are added to or removed from the list. The <li> elements are wrapped in a <transition-group> whose name attribute determines the CSS animation names and whose tag attribute is the parent <ul>.

<transition-group name="list" tag="ul">
  <li v-for="(item, index) in activeHeadings" v-bind:key="item.id">
    <a :href="item.id">
      {{ item.text }}
    </a>
  </li>
</transition-group>

Entering and leaving elements start invisible (opacity: 0) and shifted slightly downward (transform: translateY(10px)).

.list-enter, .list-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

Only transform and opacity are animated, for performance. The two transitions use different durations: 0.8 seconds for transform and 0.4s for the fade.

.list-leave-active, .list-move {
  transition: transform 0.8s, opacity 0.4s;
}

A short delay on newly added elements lets subheadings fade in after the parent heading has moved. The v-enter-active hook provides it:

.list-enter-active { 
  transition: transform 0.8s ease 0.4s, opacity 0.4s ease 0.4s;
}

Leaving elements get absolute positioning so the remaining entries do not jump when the list reflows:

.list-leave-active {
  position: absolute;
}

Since the scrolling interaction fades elements in and out, rapid scrolling can leave unfinished animations overlapping newer ones. Debouncing the interaction avoids this; either a hand-written debounce or lodash's debounce works. The simplest fix for the example is to wrap the Intersection Observer callback in a debounce function and pass the debounced version to the observer.

const debouncedFunction = _.debounce(this.handleObserver)
this.observer = new IntersectionObserver(debouncedFunction,options)