Last active
February 12, 2020 09:27
-
-
Save piranha/5623220 to your computer and use it in GitHub Desktop.
Anchorify.js
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
/* | |
* 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