{"id":325013,"date":"2020-11-13T07:59:31","date_gmt":"2020-11-13T15:59:31","guid":{"rendered":"https:\/\/css-tricks.com\/?p=325013"},"modified":"2020-11-13T07:59:34","modified_gmt":"2020-11-13T15:59:34","slug":"parsing-markdown-into-an-automated-table-of-contents","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/parsing-markdown-into-an-automated-table-of-contents\/","title":{"rendered":"Parsing Markdown into an Automated Table of Contents"},"content":{"rendered":"\n
A table of contents is a list of links that allows you to quickly jump to specific sections of content on the same page. It benefits long-form content because it shows the user a handy overview of what content there is with a convenient way to get there.<\/p>\n\n\n\n
This tutorial will show you how to parse long Markdown text to HTML and then generate a list of links from the headings. After that, we will make use of the Intersection Observer API to find out which section is currently active, add a scrolling animation when a link is clicked, and finally, learn how Vue\u2019s On the web, text content is often delivered in the form of Markdown. If you haven\u2019t used it, there are lots of reasons<\/a> why Markdown is an excellent choice for text content. We are going to use a markdown parser called marked<\/a>, but any other parser<\/a> is also good. <\/p>\n\n\n\n We will fetch our content from a Markdown file on GitHub. After we loaded our Markdown file, all we need to do is call the After we fetch and parse our data, we will pass the parsed HTML to our DOM by replacing the content with <transition-group><\/code> allow us to create a nice animated list depending on which section is currently active.<\/p>\n\n\n\n\n\n\n
Parsing Markdown<\/h3>\n\n\n
marked(<markdown>, <options>)<\/code> function to parse the Markdown to HTML.<\/p>\n\n\n\n
async function fetchAndParseMarkdown() {\n\u00a0 const url = 'https:\/\/gist.githubusercontent.com\/lisilinhart\/e9dcf5298adff7c2c2a4da9ce2a3db3f\/raw\/2f1a0d47eba64756c22460b5d2919d45d8118d42\/red_panda.md'\n\u00a0 const response = await fetch(url)\n\u00a0 const data = await response.text()\n\u00a0 const htmlFromMarkdown = marked(data, { sanitize: true });\n\u00a0 return htmlFromMarkdown\n}<\/code><\/pre>\n\n\n\n
innerHTML<\/code>.<\/p>\n\n\n\n
async function init() {\n\u00a0 const $main = document.querySelector('#app');\n\u00a0 const htmlContent = await fetchAndParseMarkdown();\n\u00a0 $main.innerHTML = htmlContent\n}\n\u2028\ninit();<\/code><\/pre>\n\n\n\n