Created
May 6, 2016 14:36
-
-
Save andreasvirkus/734b40eee5bb26bd5e6794d0f20e73e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Create permalinks for headings | |
* This snippet presumes the headings already have IDs | |
* (through Markdown or the likes). | |
* | |
* Sample styles are in the gist permalink.css | |
* https://gist.github.com/andreasvirkus/770004dc0180fba206933e3e48d3402b | |
* | |
* Dependencies: Font-Awesome (fa fa-link) for hyperlink symbols | |
*/ | |
// vanilla | |
var anchorForId = function (id) { | |
var anchor = document.createElement("a"); | |
anchor.className = "permalink"; | |
anchor.href = "#" + id; | |
anchor.innerHTML = "<i class=\"fa fa-link\"></i>"; | |
return anchor; | |
}; | |
var linkifyAnchors = function (level, containingElement) { | |
var headers = containingElement.getElementsByTagName("h" + level); | |
for (var h = 0; h < headers.length; h++) { | |
var header = headers[h]; | |
if (typeof header.id !== "undefined" && header.id !== "") { | |
header.appendChild(anchorForId(header.id)); | |
} | |
} | |
}; | |
document.onreadystatechange = function () { | |
if (this.readyState === "complete") { | |
var contentBlock = document.getElementsByClassName("docs")[0] || document.getElementsByClassName("news")[0]; | |
if (!contentBlock) { | |
return; | |
} | |
for (var level = 1; level <= 6; level++) { | |
linkifyAnchors(level, contentBlock); | |
} | |
} | |
}; | |
// jQuery | |
$(function() { | |
return $("h2, h3, h4, h5, h6").each(function(i, el) { | |
var $el = $(el), | |
id = $el.attr('id'), | |
icon = '<i class="fa fa-link"></i>'; | |
if (id) { | |
return $el.prepend($("<a />").addClass("permalink").attr("href", "#" + id).html(icon)); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment