forked from phaserjs/phaser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoc.js
100 lines (87 loc) · 2.61 KB
/
toc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
(function($) {
$.fn.toc = function(options) {
var self = this;
var opts = $.extend({}, jQuery.fn.toc.defaults, options);
var container = $(opts.container);
var headings = $(opts.selectors, container);
var headingOffsets = [];
var activeClassName = opts.prefix+'-active';
var scrollTo = function(e) {
if (opts.smoothScrolling) {
e.preventDefault();
var elScrollTo = $(e.target).attr('href');
var $el = $(elScrollTo);
$('body,html').animate({ scrollTop: $el.offset().top }, 400, 'swing', function() {
location.hash = elScrollTo;
});
}
$('li', self).removeClass(activeClassName);
$(e.target).parent().addClass(activeClassName);
};
//highlight on scroll
var timeout;
var highlightOnScroll = function(e) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
var top = $(window).scrollTop(),
highlighted;
for (var i = 0, c = headingOffsets.length; i < c; i++) {
if (headingOffsets[i] >= top) {
$('li', self).removeClass(activeClassName);
highlighted = $('li:eq('+(i-1)+')', self).addClass(activeClassName);
opts.onHighlight(highlighted);
break;
}
}
}, 50);
};
if (opts.highlightOnScroll) {
$(window).bind('scroll', highlightOnScroll);
highlightOnScroll();
}
return this.each(function() {
//build TOC
var el = $(this);
var ul = $('<ul/>');
headings.each(function(i, heading) {
var $h = $(heading);
headingOffsets.push($h.offset().top - opts.highlightOffset);
//add anchor
var anchor = $('<span/>').attr('id', opts.anchorName(i, heading, opts.prefix)).insertBefore($h);
//build TOC item
var a = $('<a/>')
.text(opts.headerText(i, heading, $h))
.attr('href', '#' + opts.anchorName(i, heading, opts.prefix))
.bind('click', function(e) {
scrollTo(e);
el.trigger('selected', $(this).attr('href'));
});
var li = $('<li/>')
.addClass(opts.itemClass(i, heading, $h, opts.prefix))
.append(a);
ul.append(li);
});
el.html(ul);
});
};
jQuery.fn.toc.defaults = {
container: 'body',
selectors: 'h1,h2,h3',
smoothScrolling: true,
prefix: 'toc',
onHighlight: function() {},
highlightOnScroll: true,
highlightOffset: 100,
anchorName: function(i, heading, prefix) {
return prefix+i;
},
headerText: function(i, heading, $heading) {
return $heading.text();
},
itemClass: function(i, heading, $heading, prefix) {
return prefix + '-' + $heading[0].tagName.toLowerCase();
}
};
})(jQuery);