Last active
May 5, 2019 17:06
-
-
Save MightyPork/f9ad638f83117c05d368 to your computer and use it in GitHub Desktop.
Add "id" to headings and scroll to heading based on URL
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
function headingAnchors(self_link_text) { | |
self_link_text = self_link_text || '#'; | |
var headings = document.querySelectorAll('h1, h2, h3, h4, h5'); | |
for (var i = 0; i < headings.length; i++) { | |
var e = headings[i]; | |
if (!e.id) { | |
var tc = e.textContent; | |
tc = tc.replace(/[^a-z0-9-]/gi, '-') | |
.replace(/-{2,}/gi, '-') | |
.replace(/-+$/gi, '') | |
.toLowerCase(); | |
e.id = tc; | |
var a = document.createElement('a'); | |
a.href = '#' + tc; | |
a.target = "_self"; | |
a.textContent = self_link_text; | |
e.appendChild(a); | |
} | |
} | |
// Scroll to the given hash | |
var h = location.hash; | |
location.hash = ''; | |
location.hash = h; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment