Hi All,
I’m trying to create a floating Table of content based on H2 & H3 in the rich text from CMS.
I did all the steps but it doesn’t seem to work for me
Tried both and the content table wasn’t generated at all not sure what I’m doing wrong.
Currently I just have another rich text links linking to anchors - but apparently that doesn’t work from one rich text to another.
In my main text, I have titles (H2) and subtitles (H3). I would like to display only the titles (H2) in the Table of Contents. Is it possible? If yes, how can I do it?
By default, the code in this project is only supposed to target H2’s.
document.getElementById("content").querySelectorAll("h2").forEach(function(heading, i) { // runs a function for all h2 elements inside your rich text element
<script>
document.getElementById("content").querySelectorAll("{{wf {"path":"toc-based-on","type":"PlainText"\} }}").forEach(function(heading, i) { // runs a function for all headings inside your rich text element
observer.observe(heading);
let str = heading.innerHTML; // adds section titles to slugs
str = str.replace(/\s+/g, '-').replace(/[°&\/\\#,+()$~%.'":;*?<>{}]/g, "").toLowerCase(); // replaces spaces with hyphens, removes special characters and extra spaces from the headings, and applies lowercase in slugs
heading.setAttribute("id", str); // gives each heading a unique id
const item = document.createElement("a"); // creates an anchor element called "item" for each heading
item.innerHTML = heading.innerHTML; // gives each item the text of the corresponding heading
("{{wf {"path":"toc-based-on","type":"PlainText"\} }}").split(",").forEach(function(x) { // runs a function for each item in your headings list
if (heading.tagName.toLowerCase()==x) {
item.classList.add("tocitem", "toc-" + x); // gives each item the correct class
}
});
item.setAttribute("href", "#" + str); // gives each item the correct anchor link
document.querySelector("#toc").appendChild(item); // places each item inside the Table of Contents div
});
</script>
I have put “H2” in the function you quoted. But still it displays also H3 titles in the TOC.
Actually the Finsweet plugin cannot work for me. I create my blog articles using the CMS. With the Finsweet plugin, we need to give the titles a personalised attribute. It seems it is not possible when using the CMS, which is a single ‘Rich Text’ block.
Furthermore, the Finsweet plugin is expensive: $199 per year if I want to be able to use it on a custom domain.
So Duncan, I am still interested in your solution, if you have one!
I’m just not understanding how to go from a static blog post (which I can get to work) to a Blog Post template page where these TOC links are generated dynamically based on what’s in the Rich Text of my Blog Post.