Last active
August 29, 2015 14:06
-
-
Save mikofski/12d629f401e860726476 to your computer and use it in GitHub Desktop.
generate table of contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<!-- either head or body --> | |
<style type="text/css"> | |
.toc_item { | |
color: green; | |
} | |
</style> | |
<!-- css class --> | |
</head> | |
<body> | |
<div id="toc"> | |
</div> | |
<!-- TOC --> | |
<h2 class="toc_item">item #1</h2> | |
<p>Item 1 is very cool.</p> | |
<!-- item #1 --> | |
<h3 class="toc_item">item #2</h3> | |
<p>Item 2 is super fun.</p> | |
<!-- item #2 --> | |
<h2 class="toc_item"><a href="http://www.example.com">item #3</a></h2> | |
<p>Item 3 is awesome.</p> | |
<!-- item #3 --> | |
<!-- content --> | |
<script> | |
/* Generate TOC | |
* | |
* :param classname: Class to which all TOC items belong. | |
* :param tocID: ID of the TOC element, should be <div></div>. | |
*/ | |
function gen_toc(classname, tocID) { | |
var alltags = document.getElementsByClassName(classname); // all TOC items | |
var toc_content = "<h2>Table of Contents</h2><ol>"; // inner HTML content of TOC element | |
var toc_link = ' <a href="#' + tocID + '">(' + tocID + ')</a>'; // link to TOC element for each TOC item | |
for (var i = 0; i < alltags.length; i++) { | |
var toc_item = alltags[i].innerText; // just the inner text from the TOC item's element, ie: no links | |
var toc_item_enc = encodeURIComponent(toc_item).replace(" ", "-").toLowerCase(); // make URL safe ID string | |
alltags[i].setAttribute("id", toc_item_enc); // set ID of TOC item | |
alltags[i].innerHTML += toc_link; // add back link to TOC from TOC item | |
toc_content += '<li><a href="#'; | |
toc_content += toc_item_enc; | |
toc_content += '">'; | |
toc_content += toc_item; | |
toc_content += '</a></li>'; | |
}; | |
toc_content += '</ol>'; | |
console.log(toc_content); | |
var toc = document.getElementById(tocID); // TOC element | |
toc.innerHTML = toc_content; | |
}; | |
document.body.onload = gen_toc("toc_item", "toc"); | |
</script> | |
<!-- toc script --> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment