Skip to content

Instantly share code, notes, and snippets.

@piranha
Last active February 12, 2020 09:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piranha/5623220 to your computer and use it in GitHub Desktop.
Save piranha/5623220 to your computer and use it in GitHub Desktop.
Anchorify.js
/*
* Anchorify without jQuery
* Rewritten from https://github.com/willdurand/anchorify.js/
*/
var anchorify = (function() {
var specialCharsRe = /[ ;,.'?!_]/g;
function generateId(text) {
return text
.trim()
.replace(specialCharsRe, '-')
.replace(/[\-]+/g, '-')
.replace(/-$/, '')
.toLowerCase();
}
function uniqId(id) {
var inc = 1,
original = id;
while (document.getElementById(id)) {
id = original + '-' + inc++;
}
return id;
}
function getText(el) {
var node;
for (var i = 0; i < el.childNodes.length; i++) {
node = el.childNodes[i];
if (node.nodeType === Node.TEXT_NODE) {
return node.nodeValue;
}
}
}
return function(options) {
options = options || {};
var text = options.text || '¶',
className = options.className || 'anchor-link',
processExisting = options.processExisting,
sel = options.sel || 'h1, h2, h3, h4, h5',
els = document.querySelectorAll(sel);
var el, id, anchor;
for (var i = 0; i < els.length; i++) {
el = els[i];
console.log(el);
if (el.id && !processExisting) {
continue;
}
el.id = el.id || uniqId(generateId(getText(el)));
anchor = document.createElement('a');
anchor.className = className;
anchor.href = '#' + el.id;
anchor.innerHTML = text;
if (options.position == 'prepend') {
el.insertBefore(anchor, el.firstChild);
} else {
el.appendChild(anchor);
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment