Created
June 10, 2015 10:34
-
-
Save Langmans/b3b99ba580fdc0831be0 to your computer and use it in GitHub Desktop.
a very simple 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
jQuery(function ($) { | |
var $headings = $('h1, h2, h3', '#content'); | |
var $h2 = $('h2', '#content'); | |
// Only if two or more level 2 headings. | |
// and if content is larger then window. | |
if (($h2.length > 1 || $headings.length > 6) && $('#content').height() > $(window).height() * 1.25) { | |
var $nav = $('<nav>').attr('id', 'toc'); | |
$nav.insertAfter('#sidebar'); | |
(function ($nav, $headings) { | |
var slugify = function (str) { | |
str = str.replace(/^\s+|\s+$/g, ''); // trim | |
str = str.toLowerCase(); | |
// remove accents, swap ñ for n, etc | |
var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;"; | |
var to = "aaaaaeeeeeiiiiooooouuuunc------"; | |
for (var i = 0, l = from.length; i < l; i++) { | |
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); | |
} | |
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars | |
.replace(/\s+/g, '-') // collapse whitespace and replace by - | |
.replace(/-+/g, '-') // collapse dashes | |
.replace(/^-+|-+$/, ''); // trim | |
return str; | |
}; | |
$headings.each(function (i) { | |
var $heading = $(this); | |
var text = $heading.text(); | |
var level = $heading.prop("tagName").replace(/[^0-9]/, ''); | |
//if (level == 1) { | |
// $nav.append('<strong>Op deze pagina: ' + text + '</strong>'); | |
// return; | |
//} | |
var slug = $heading.attr('id'); | |
if (!slug || slug.replace(/^\s+|\s+$/g, '') == '') { | |
var slug = 'toc' + (i + 1) + '-' + slugify(text); | |
$heading.attr('id', slug); | |
} | |
if (level < 3) { | |
$heading.prepend($('<a>↑ Terug naar boven</a>').addClass('toc-up-arrow').attr('href', '#' + $nav.attr('id'))); | |
} | |
$('<a> ').addClass('level' + level).attr('href', '#' + slug).text(text).appendTo($nav); | |
}); | |
})($nav, $headings); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment