-
Notifications
You must be signed in to change notification settings - Fork 6
/
anchorify.min.js
executable file
·92 lines (74 loc) · 2.54 KB
/
anchorify.min.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
/*!
* William DURAND <william.durand1@gmail.com>
* MIT Licensed
*/
(function (document, $) {
"use strict";
var anchorify = (function() {
var _specialCharsRegex = /[ ;,.'?!_]/g;
function generateId(text) {
return text
.trim()
.replace(_specialCharsRegex, '-')
.replace(/[-]+/g, '-')
.replace(/-$/, '')
.toLowerCase();
}
function uniqId(id) {
var inc = 1,
originalId = id;
while (document.getElementById(id)) {
id = originalId + '-' + inc++;
}
return id;
}
function getText( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += getText( elem.childNodes );
}
}
return ret;
}
return function anchorify(els, options) {
var text = options.text || '¶',
cssClass = options.cssClass || 'anchor-link',
skipExisting = options.skipExisting;
var el, id, anchor;
for (var i = 0; i < els.length; i++) {
el = els[i];
if (el.id && skipExisting) {
continue;
}
el.id = el.id || uniqId(generateId(getText([el])));
anchor = document.createElement('a');
anchor.className = cssClass;
anchor.href = '#' + el.id;
anchor.innerHTML = text;
if (options.position == 'prepend') {
el.insertBefore(anchor, el.firstChild);
} else {
el.appendChild(anchor);
}
}
};
})();
if (typeof $ !== 'undefined') {
$.fn.anchorify = function (options) {
anchorify($(this).get(), options || {});
return this;
};
} else {
window.anchorify = function(options) {
options = options || {};
var els = document.querySelectorAll(options.sel || 'h1, h2, h3, h4, h5');
return anchorify(els, options);
};
}
})(document, jQuery);