How we can generate an automatic table of contents using HTML CSS JS? Solution: See this Dynamic Table Of Contents With Active Link Highlight, Automatic Table.
Previously I have shared many types of tables, but this is an auto-generated table of contents. Basically a dynamic table of contents creates table items automatically of content’s heading. And these table items help you to directly navigate to the content. If you are using any CMS like WordPress then there are many plugins to do that. But we can create this for a normal website using pure JavaScript.
Today you will learn to create an automatic table of contents using JS. Basically, there are two sections one is a normal body section which contains heading and texts, and one is a sidebar that contains the table. There is not an ID and hyperlink target method, all the table items generated automatically by JavaScript. You can directly navigate to a specific section by clicking the table item link. Also when you will scroll manually, then you can see the active link because there is a color fill indicator.
So, Today I am sharing Dynamic Table Of Contents With Active Link Highlight. There I have used HTML to create the layout and contents, CSS for styling, and JavaScript for functioning. There is a completely dynamic feature to create table items and link targeting. You can use it on your website or posts to create the post content structure.
If you are thinking now how this dynamic structure actually is, then see the preview given below.
Preview Of Automatic Table Structure
See this video preview to getting an idea of how this table structure program looks like.
Now you can see this program visually, also you can see it live by pressing the button given above. If you like this then get the source code of its.
You May Also Like:
Dynamic Table Of Contents Source Code
Before sharing source code, let’s talk about it. First I have created a nav using HTML <nav> tag for creating the dynamic table, and placed many headings and paragraphs to create the contents. Also, there I have placed some list items using <ul> & <li> tags. There I have not placed any ID or class name in the headings or any other items. Also, In the HTML file, I have linked other files like CSS and JS.
Now using CSS I have placed all the items in the right place, as you can see in the preview. With CSS first I gave basic values like size, position, margin, padding, etc to the elements. There gave a color for an active link, and the elements are creating by JS dynamically. There I have used flex display command to create a flexible layout.
JavaScript handling here the main feature in the program. First of all, I want to tell you, the JS codes are complicated if you don’t have good knowledge of JS then you can’t get this. There JS fetched all the headings using querySelectorAll command. Also, I have used JS if{} else{} statements multiple times.
Left all other things you will understand after getting the codes, I can’t explain all in writing. For creating the program you have to create 3 files. First file for HTML, second for CSS, and third file for JavaScript. Follow the steps to creating this program without any error.
index.html
Create an HTML file named ‘index.html‘ and put these codes given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
<!DOCTYPE html> <!-- Code By Webdevtrick ( https://webdevtrick.com )--> <html lang="en" > <head> <meta charset="UTF-8"> <title>Dynamic Active Table Of Contents | Webdevtrick.com</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css2?family=Poppins&family=Teko:wght@600&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css"> </head> <body> <nav id="toc"> </nav> <main> <h1>New Horizons</h1> <p> Live life at your own pace as you garden, fish, decorate, hunt for bugs and fossils, get to know the animal residents, and more. The time of day and seasons match real life, so something is happening on your island whether you’re there or not. </p> <p>Oh--just watch out for those shifty racoons.</p> <h2>Tools</h2> <p>New Horizons has all sorts of tools that you can use to your disposal!</p> <h3>Shovel</h3> <p>This tool's versatility knows no bounds! Hole digging, rock smacking, tree uprooting goodness!</p> <h3>Bug Net</h3> <p>Catch some bugs--if you are into that kind of thing.</p> <h3>Slingshot</h3> <p>Make presents fall from the sky! Just watch out for the river!</p> <h3>Fishing Rod</h3> <p>After all that shovel work its nice to take a load of, craft a nice coconut juice, and fish.</p> <h3>Ladder</h3> <p>For those annoying cliffs.</p> <h3>Axe</h3> <p>For choppin' trees--just watch out for them bees!</p> <h3>Vaulting Pole</h3> <p>For those like me, that are too poor to afford a bridge.</p> <h3>Watering Can</h3> <p>Those flowers won't crossbreed themselves.</p> <h2>Flower Crossbreeding</h2> <h3>Lilies</h3> <ul> <li>Red + Red = Black</li> <li>Yellow + Red = Orange</li> <li>Red + White = Pink</li> </ul> <h3>Roses</h3> <ul> <li>Red + Red = Black</li> <li>Red + White = Pink</li> <li>Yellow + Red = Orange</li> <li>White + White = Purple</li> </ul> <h3>Mums</h3> <ul> <li>White + Red = Pink</li> <li>White + White = Purple</li> <li>Purple + Purple = Green</li> </ul> <h3>Pansies</h3> <ul> <li>Red + Red = Purple</li> <li>White + White = Blue</li> <li>Yellow + Red = Orange</li> <li>Blue + Blue = Purple</li> <li>Red + Red = Purple</li> </ul> <h3>Windflower</h3> <ul> <li>Orange + Red = Pink</li> <li>Orange + White = Blue</li> <li>White + White = Blue</li> <li>Blue + Pink = Purple</li> <li>Blue + Blue = Purple</li> </ul> <h3>Hyacinths</h3> <ul> <li>Red + White = Pink</li> <li>White + White = Blue</li> <li>Red + Yellow = Orange</li> <li>Blue + Blue = Purple</li> </ul> <h3>Cosmos</h3> <ul> <li>Yellow + Red = Orange</li> <li>Red + White = Pink</li> <li>Red + Red = Black</li> </ul> <h3>Tulips</h3> <ul> <li>Red + Red = Black</li> <li>Red + Yellow = Orange</li> <li>Red + White = Pink</li> <li>Black + Black = Purple</li> </ul> </main> <script src="function.js"></script> </body> </html> |
style.css
Now create a CSS file named ‘style.css‘ and put these codes given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
/* Code By Webdevtrick ( https://webdevtrick.com ) */ body { display: flex; flex-flow: space-between; height: 100vh; font-family: 'Poppins', sans-serif; margin: 0; color: #333344; line-height: 1.53em; font-size: 1.2rem; background-color: #efeeff; } h1, h2, h3, h4, h5, h6 { font-family: 'Teko', sans-serif; font-weight: 300; margin-top: 3rem; color: #484866; } main { flex: 3 3 100%; overflow: auto; padding: 2rem 3rem; } nav { flex: 1 1 300px; background-color: #333344; min-width: 240px; padding: 1rem; overflow-y: auto; } h1, h2, p { max-width: 700px; } a { color: #eeeeff; text-decoration: none; } .active { color: #ff8888; font-weight: bold; } ul { list-style: none; padding-left: 1.25rem; } ul li::before { content: "\2022"; color: #eeeeff; font-weight: bold; display: inline-block; width: 1em; margin-left: -1em; } |
function.js
The final step, create a JavaScript file named ‘function.js‘ and put the codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
// Code By Webdevtrick ( https://webdevtrick.com ) let tocId = "toc"; let headings; let headingIds = []; let headingIntersectionData = {}; let headerObserver; function setLinkActive(link) { const links = document.querySelectorAll(`#${tocId} a`); links.forEach((link) => link.classList.remove("active")); if (link) { link.classList.add("active"); } } function getProperListSection(heading, previousHeading, currentListElement) { let listSection = currentListElement; if (previousHeading) { if (heading.tagName.slice(-1) > previousHeading.tagName.slice(-1)) { let nextSection = document.createElement("ul"); listSection.appendChild(nextSection); return nextSection; } else if (heading.tagName.slice(-1) < previousHeading.tagName.slice(-1)) { let indentationDiff = parseInt(previousHeading.tagName.slice(-1)) - parseInt(heading.tagName.slice(-1)); while (indentationDiff > 0) { listSection = listSection.parentElement; indentationDiff--; } } } return listSection; } function setIdFromContent(element, appendedId) { if (!element.id) { element.id = `${element.innerHTML .replace(/:/g, "") .trim() .toLowerCase() .split(" ") .join("-")}-${appendedId}`; } } function addNavigationLinkForHeading(heading, currentSectionList) { let listItem = document.createElement("li"); let anchor = document.createElement("a"); anchor.innerHTML = heading.innerHTML; anchor.id = `${heading.id}-link`; anchor.href = `#${heading.id}`; anchor.onclick = (e) => { setTimeout(() => { setLinkActive(anchor); }); }; listItem.appendChild(anchor); currentSectionList.appendChild(listItem); } function buildTableOfContentsFromHeadings() { const tocElement = document.querySelector(`#${tocId}`); const main = document.querySelector("main"); if (!main) { throw Error("A `main` tag section is required to query headings from."); } headings = main.querySelectorAll("h1, h2, h3, h4, h5, h6"); let previousHeading; let currentSectionList = document.createElement("ul"); tocElement.appendChild(currentSectionList); headings.forEach((heading, index) => { currentSectionList = getProperListSection( heading, previousHeading, currentSectionList ); setIdFromContent(heading, index); addNavigationLinkForHeading(heading, currentSectionList); headingIds.push(heading.id); headingIntersectionData[heading.id] = { y: 0 }; previousHeading = heading; }); } function updateActiveHeadingOnIntersection(entry) { const previousY = headingIntersectionData[entry.target.id].y; const currentY = entry.boundingClientRect.y; const id = `#${entry.target.id}`; const link = document.querySelector(id + "-link"); const index = headingIds.indexOf(entry.target.id); if (entry.isIntersecting) { if (currentY > previousY && index !== 0) { console.log(id + ":1 enter top"); } else { console.log(id + ":2 enter bottom"); setLinkActive(link); } } else { if (currentY > previousY) { console.log(id + ":3 leave bottom"); const lastLink = document.querySelector(`#${headingIds[index - 1]}-link`); setLinkActive(lastLink); } else { console.log(id + ":4 leave top"); } } headingIntersectionData[entry.target.id].y = currentY; } function observeHeadings() { let options = { root: document.querySelector("main"), threshold: 0.1 }; headerObserver = new IntersectionObserver( (entries) => entries.forEach(updateActiveHeadingOnIntersection), options ); Array.from(headings) .reverse() .forEach((heading) => headerObserver.observe(heading)); } window.addEventListener("load", (event) => { buildTableOfContentsFromHeadings(); if ("IntersectionObserver" in window) { observeHeadings(); } }); window.addEventListener("unload", (event) => { headerObserver.disconnect(); }); |
That’s It. Now you have successfully create Dynamic Table Of Contents With Active Link Highlight, Automatic Table generate program. If you have doubt or question comment down below.
Thank For Visiting, Keep Visiting.
how does the active link index start from firstlink?
how to make an active link starting from the top not from the bottom?
yeah, the first item which is highlighted is Ladder (5th element)
so thanks, but no
I resolve an issue with the highlighting by changing .replace(/:/g, “”) to .replace(/[^a-zA-Z ]/g, “”)
Unfortunately anchor links in the html page are not appearing because the link color is getting changed. Can you please fix it.