In this article, we will discuss how to add table of contents to Ghost CMS blog post.
- Login to your Ghost platform.
- While writing your article, use H1 and H2 tags as needed.
- Once you complete the post, add the following code to the end of the post.
- Click on the + button and click add HTML.
- Add the following code.
- <script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js” integrity=”sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=” crossorigin=”anonymous”></script>
<script>
var contentsTitle = “Table of Contents”; // Set your title here, to avoid making a heading for it later
var ToC = “<h2>”+contentsTitle+”</h2>”;
ToC += “<nav role=’navigation’ class=’table-of-contents’><ul>”;
var first = false;
$(“h2,h3″).each(function() {
var el = $(this);
if (first === false) {
first = true;
$(‘<span id=”dynamictoc”></span>’).insertBefore(el);
}
var title = el.text();
var link = “#” + el.attr(“id”);
if (el.is(“h2”)) {
ToC += “<li><a href='” + link + “‘>” + title + “</a></li>”;
} else if (el.is(“h3”)) {
ToC += “<li style=’margin-left:2em’><a href='” + link + “‘>” + title + “</a></li>”;
}
});
ToC += “</ul></nav>”;
console.log(ToC);
$(“#dynamictoc”).html(ToC);
</script>
- <script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js” integrity=”sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=” crossorigin=”anonymous”></script>