Skip to content

Instantly share code, notes, and snippets.

@sblack4
Created January 19, 2018 15:37
Show Gist options
  • Save sblack4/88b613ffe25b4a215e3d62ec51b2af7f to your computer and use it in GitHub Desktop.
Save sblack4/88b613ffe25b4a215e3d62ec51b2af7f to your computer and use it in GitHub Desktop.
add github flavored heading anchors
// Hack to make intra-page links work
// replaces id's after angular strips them out
/**
* Given a Node, returns a
* GitHub flavored heading anchor
* @param {Node}
* @returns {string}
*/
function getHeadingAnchor(domNode) {
var currentHeaderTextContent = domNode.textContent.trim();
return currentHeaderTextContent.replace(/\W+/g, "-");
}
/**
* Given a Node, adds a
* GitHub flavored heading anchor
* @param {Node}
*/
function anchorHeadingNode(domNode) {
try {
var anchorText = getHeadingAnchor(domNode);
domNode.setAttribute("id", anchorText);
} catch (err) {
if(!err) return;
console.error(err);
}
}
/**
* Loops through Header 1-3 NodeList
* and adds GitHub flavored heading anchor
*/
function anchorHeadingNodes() {
var headersThatNeedID = "h1, h2, h3";
var headerCollection = document.querySelectorAll(headersThatNeedID);
for(var i=0; i < headerCollection.length; i++) {
var currentHeader = headerCollection[i];
anchorHeadingNode(currentHeader);
}
}
// document.ready fires too soon
// must wait for external (angular) content to load
window.onload = anchorHeadingNodes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment