Dynamic Table of Content
Not working on site?
by Imri Paloja
HTML
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<article>
<h1>blahblah</h1>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
<h3 id="one">How does one kiss smurf a murf?</h3>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
<h3 id="two">How do many licks does a giraffe?</h3>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
<h3 id="three">Which Frank is?</h3>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
<h3 id="four">Is fourteen enough?</h3>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
<h3 id="five">Is a circle an oval y/n?</h3>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero...
CSS
body {
background: #eee;
padding: 20px;
}
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;
}
}
JavaScript
var ToC =
"<nav role='navigation' class='table-of-contents'>" +
"<h2>On this page:</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>";
$("article").prepend(ToC);