Skip to content

Instantly share code, notes, and snippets.

@ngalluzzo
Created August 18, 2016 22:51
Show Gist options
  • Select an option

  • Save ngalluzzo/c89f0d0200acfd30a1c0cb051e8825db to your computer and use it in GitHub Desktop.

Select an option

Save ngalluzzo/c89f0d0200acfd30a1c0cb051e8825db to your computer and use it in GitHub Desktop.
Zendesk TOC
var $headers = $('.article-body h1');
if ($headers.length > 1) {
var $toc = $('<div class="toc">');
var $firstUl = $('<ul>');
var $currentUl = $firstUl;
var previous_level = 1;
$firstUl.appendTo($toc);
$toc.prependTo('section.article-info');
// start with first H1
insertHeading($headers[0]);
}
function insertHeading(heading) {
var $heading = $(heading);
// what level heading are we on?
var current_level = headingLevel(heading);
// if it's an H1, add it to the original list
if (current_level === 1) {
newLi($heading, $firstUl);
$currentUl = $firstUl;
}
// if it's the same as the one before it, add it to the current list
else if (current_level === previous_level) {
newLi($heading, $currentUl);
}
// if it's one level higher than the one before it... time to make a new nested list
else if (current_level > previous_level) {
nestUl();
newLi($heading, $currentUl);
}
previous_level = current_level;
var $nextHeading = $heading.nextAll("h1, h2, h3, h4, h5, h6").first()[0];
// if there's any headings left... run this again
if ($nextHeading) insertHeading($nextHeading);
}
// adds a new UL to the current UL
function nestUl() {
var $newUl = $('<ul>');
$newUl.appendTo($currentUl);
$currentUl = $newUl;
}
// returns a numerical value for each heading
function headingLevel(heading) {
switch (heading.nodeName) {
case 'H1':
return 1;
break;
case 'H2':
return 2;
break;
case 'H3':
return 3;
break;
case 'H4':
return 4;
break;
case 'H5':
return 1;
break;
case 'H6':
return 6;
break;
default:
return 0;
}
}
// inserts a new line to the current list
function newLi(heading, $list) {
var $heading = $(heading);
var $wrapper = $('<li></li>');
var $link = $('<a>').prop('href', '#' + $heading.prop('id'));
$link.html('<span class="index"></span> ' + $heading.text());
.appendTo($wrapper);
$wrapper.appendTo($list);
var place_in_parent = $list.children('li').length;
if ($list.parent()[0].nodeName === 'DIV') {
$link.find('.index').text(place_in_parent)
} else {
$link.find('.index').text($wrapper.parent().prev('li').find('.index').text() + '.' + place_in_parent)
}
$heading.text($link.find('.index').text() + ' ' + $heading.text());
}
@bysty
Copy link

bysty commented Jan 27, 2017

I am getting this error:

  $link.html('<span class="index"></span> ' + $heading.text());
       .appendTo($wrapper);

Uncaught SyntaxError: Unexpected token .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment