Blogging-Create Table of Contents

Steps to create table of contents in a blog post:


Add below css at the end of Head tag i.e just before</head> by editng the Theme as HTML.

CSS


<style>
article {
  max-width: 50em;
  background: white;
  padding: 2em;
  margin: 1em auto;
}
.table-of-contents {
  float: right;
  width: 40%;
  background: #eee;
  font-size: 0.8em;
  padding: 1em 2em;
  margin: 0 0 0.5em 0.5em;
}
.table-of-contents ul {
  padding: 0;
}
.table-of-contents li {
  margin: 0 0 0.25em 0;
}
.table-of-contents a {
  text-decoration: none;
}
.table-of-contents a:hover,
.table-of-contents a:active {
  text-decoration: underline;
}

h3:target {
  animation: highlight 1s ease;
}

@keyframes highlight {
  from { background: yellow; }
  to { background: white; }
}
</style>

Add below JavaScript just before </body> i.e body tag ending.

JavaScript


<script type='text/javascript'>
var ToC =
  "<nav class='table-of-contents' role='navigation'>" +
    "<h2>Table of Contents:</h2>" +
    "<ul>";

var newLine, el, title, link;

$("article h3").each(function() {

  el = $(this);
  title = el.text();
  link = "#" + el.attr("id");

  newLine =
    "<li>" +
      "<a href='" + link + "'>" +
        title +
      "</a>" +
    "</li>";

  ToC += newLine;

});

ToC +=
   "</ul>" +
  "</nav>";

$(".all-questions").prepend(ToC);
</script>

Add below HTML <article> tag before the start of the post and </article> at the end of the post in HTML.
Then Add  <div class="all-questions"> at the place where you would like to see table of contents and then add closing tag </div> just before the </article> tag.

HTML


<article>

<div class="all-questions">

</div>

</article>

Post a Comment

0 Comments