Practical - The automatic table of contents generator in html webpage

 

Creating an automatic table of contents (TOC) in an HTML webpage can be achieved using JavaScript. Here's a simple example:

HTML Structure

First, create the basic HTML structure with headings:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Automatic Table of Contents</title> <style> body { font-family: Arial, sans-serif; } #toc { margin-bottom: 20px; } #toc a { text-decoration: none; } h2, h3 { margin-top: 20px; } </style> </head> <body> <div id="toc"> <h2>Table of Contents</h2> <ul id="toc-list"></ul> </div> <h2>Introduction</h2> <p>This is the introduction section.</p> <h2>Chapter 1</h2> <p>Details about Chapter 1.</p> <h3>Subsection 1.1</h3> <p>Details about Subsection 1.1.</p> <h3>Subsection 1.2</h3> <p>Details about Subsection 1.2.</p> <h2>Chapter 2</h2> <p>Details about Chapter 2.</p> <script> document.addEventListener("DOMContentLoaded", function() { const tocList = document.getElementById('toc-list'); const headings = document.querySelectorAll('h2, h3'); headings.forEach(heading => { const listItem = document.createElement('li'); const anchor = document.createElement('a'); const id = heading.textContent.replace(/\s+/g, '-').toLowerCase(); heading.id = id; anchor.href = `#${id}`; anchor.textContent = heading.textContent; listItem.appendChild(anchor); tocList.appendChild(listItem); }); }); </script> </body> </html>

Explanation

  1. HTML Structure: The HTML includes various headings (h2 and h3) which will serve as the TOC items.
  2. CSS Styles: Basic styles for the TOC and headings.
  3. JavaScript:
    • It listens for the DOM content to load.
    • It selects all h2 and h3 headings.
    • It creates a list item for each heading, generates an ID based on the heading text, and appends it to the TOC.

How It Works

When the page loads, the script will generate a TOC based on the headings present in the document, allowing users to click and navigate directly to those sections.



Download now

Enjoy, follow us for more

No comments:

Post a Comment

How to make Hash objects with $H() function in JavaScript.mp4

 In JavaScript, you can create hash-like objects using the $H() function, which is commonly associated with the Prototype.js framework. How...