A table of contents, or TOC, is a useful navigation tool for long documents, allowing readers to quickly jump to different sections of the text. In markdown, a lightweight markup language used for formatting text, adding a TOC can be done using JavaScript.

First, create the structure of the TOC using HTML and CSS. This can be done by creating a container element, such as a div, and then adding nested list items for each section of the document. The list items should have hyperlinks that correspond to the sections they represent.

Next, use JavaScript to automatically generate the TOC based on the headings in the markdown document. This can be done by using the querySelectorAll method to select all the headings in the document, and then iterating over them to create the list items for the TOC.

To add the hyperlinks, use the id attribute of the heading elements. If the headings do not have an id, you can use the textContent property to generate a unique id for each heading.

Finally, use JavaScript to automatically update the TOC when the user scrolls through the document. This can be done by using the scroll event to track the user’s position and then updating the active class on the TOC list items accordingly.

Here is an example of JavaScript code that can be used to generate a TOC for a markdown document:

<div id="toc"></div>

<script>
  // Get all headings
  var headings = document.querySelectorAll("h1, h2, h3, h4, h5, h6");
  
  // Create TOC container
  var toc = document.getElementById("toc");
  
  // Iterate over headings
  for (var i = 0; i < headings.length; i++) {
    var heading = headings[i];
    
    // Create TOC list item
    var li = document.createElement("li");
    li.innerHTML = heading.textContent;
    
    // Add hyperlink to TOC list item
    var link = document.createElement("a");
    link.href = "#" + heading.id;
    link.appendChild(li);
    
    // Add TOC list item to TOC container
    toc.appendChild(link);
  }
</script>

This is a basic example of how to add a table of contents to a markdown document using JavaScript. There are many ways to customize and enhance the functionality of the TOC, such as using a library like jQuery to simplify the code, or using CSS to style the TOC. Additionally, you can also add the functionality to show and hide the TOC and make it more interactive.