Instantly share code, notes, and snippets.

Embed
What would you like to do?
<div id="toc-static"></div>
**TOC**
<div id="toc-wrapper">
<div class="header">Contents <a href="#" class="hide-btn">[hide]</a></div>
<div id="toc"></div>
</div>
<style>
#toc-wrapper {
position: fixed; top: 113px; max-width:320px; right: 28px;
border: thin solid rgba(0, 0, 0, 0.38); opacity: .8;
border-radius: 5px; background-color: #fff; padding:10px;
}
#toc-wrapper.closed {
min-width: 100px;
width: auto;
transition: width;
}
#toc-wrapper:hover{
opacity:1;
}
#toc-wrapper .header {
font-size:18px; font-weight: bold;
}
#toc-wrapper .hide-btn {
font-size: 14px;
}
</style>
<style>
ol.nested {
counter-reset: item;
list-style: none;
}
li.nested {
display: block;
}
li.nested:before {
counter-increment: item;
content: counters(item, ".")" ";
}
</style>
<script>
$(function(){
function list_el(h){
href = $(h).find('a').attr('href')
text = $(h).find('a').text()
return "<a href='" + href + "'>" + text + "</a>"
}
function lvl(header){
if (header !== undefined)
return $(header).prop('tagName').toLowerCase().substring(1);
else return 0;
}
window.toc = function(){
headers = $('h2, h3, h4');
html = "<ol class='nested'>";
$.each(headers , function(i, h) {
if (lvl(h) == lvl(headers[i+1])) {
html += "<li class='nested'>" + list_el(h) + "</li>" ;
}
else if ( lvl(h) < lvl(headers[i+1]) ) {
html += "<li class='nested'>" + list_el(h) + "<ol class='nested'>";
}
else if (lvl(h) > lvl(headers[i+1])) {
html += "<li class='nested'>"+ list_el(h) +"</li></ol></li>";
}
})
html += "</ol>"
$('#toc').html(html)
$('#toc-wrapper .header').click(function(){
$('#toc').slideToggle()
$('#toc-wrapper').toggleClass('closed')
if ($('#toc-wrapper').hasClass('closed')){
$('#toc-wrapper .hide-btn').html('[show]')
} else {
$('#toc-wrapper .hide-btn').html('[hide]')
}
return false
})
$('#toc-static').html(html)
}
toc()
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment