Dynamic generate Table of Content in one Click

How to create a dynamic table of content

To automatically generate a table of contents (TOC) for a single post page and display it in a fixed position on the left side, you can use a combination of HTML, CSS, and JavaScript. Below is a step-by-step guide to achieve this:

CSS for Fixed Position

Style the table of contents to be fixed on the left side of the page.

		html {
    scroll-behavior: smooth;
}

			#toc {
    position: fixed;
    top: 20px;
    left: 20px;
    max-width: 250px;
    background: #f9f9f9;
    padding: 10px;
    border: 1px solid #ddd;
    overflow-y: auto;
    max-height: 90vh;
}

#toc ul {
    list-style-type: none;
    padding-left: 20px;
}

#toc a {
    text-decoration: none;
    color: #333;
}

#toc a:hover {
    color: #0073e6;
} 

JavaScript to Generate Table of Content

Use JavaScript to dynamically generate the table of contents based on the headings in your post.

 
		document.addEventListener("DOMContentLoaded", function() {
    const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); // Include all heading levels
    const toc = document.getElementById('toc');
    let currentLevels = {}; // Store current level elements (h1, h2, etc.)

    headings.forEach(heading => {
        let id = heading.getAttribute('id');
        const text = heading.textContent;
        const level = heading.tagName.toLowerCase();

        if (!id) {
            // Generate ID if not present
            id = `${text.toLowerCase().replace(/\s+/g, '-')}`; // Basic slugification
            heading.id = id; // Set the ID on the heading element
            console.log(`Generated ID: ${id} for ${level}`); // Optional: Log the generated ID
        }

        // Build the TOC structure dynamically based on heading level
        let parentLi = toc; // Start at the top-level TOC
        let parentLevel = null;

        for (let i = 1; i <= 6; i++) { // Check each level up to h6
            const currentLevel = `h${i}`;
            if (level === currentLevel) break; // Found our level
            const parentLevelElement = currentLevels[currentLevel];
            if (parentLevelElement) {
                parentLi = parentLevelElement.querySelector('ul') || parentLevelElement; // Go into its ul if exist otherwise use parent itself
                parentLevel = currentLevel;
            }
        }

        const li = document.createElement('li');
        const link = document.createElement('a');
        link.href = `#${id}`;
        link.textContent = text;
        li.appendChild(link);

        if (level !== 'h1') {
            const ul = parentLi.querySelector('ul') || document.createElement('ul');
            ul.appendChild(li);
            parentLi.appendChild(ul);
        } else {
            parentLi.appendChild(li);
        }

        currentLevels[level] = li; // Store the current level element
        
    });
});

Add This html Container

<div id="toc"> <strong>Table of Contents</strong> </div>

Here automatically your table content generated.

Final Output

When you load the page, the JavaScript will generate a table of contents based on the headings (<h1>, <h2>, <h3>) in your post. The TOC will be fixed on the left side, and clicking on any item will scroll the page to the corresponding section.

Post a Comment

0 Comments