Created
October 19, 2020 18:15
-
-
Save ricealexander/2b8f9980c1cb3b670f2d2c70faf81e7b to your computer and use it in GitHub Desktop.
Subheading Jump-To Links
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
a.jump-to-anchor { | |
opacity: 0.5; | |
position: absolute; | |
margin-left: -24px; | |
display: none; | |
} | |
.ArticlePage-articleBody > h2:hover .jump-to-anchor { | |
display: block; | |
} | |
.feather-icon { | |
fill: none; | |
stroke: currentColor; | |
stroke-linecap: round; | |
stroke-linejoin: round; | |
} |
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
const linkIcon = ` | |
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" class="feather-icon"> | |
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path> | |
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path> | |
</svg>` | |
const slug = string => string | |
.replace(/\W+/g, '_') // replace non-word characters with underscores | |
.replace(/(^_|_$)/g, '') // trim leading/trailing underscores | |
const subheadings = document.querySelectorAll('.ArticlePage-articleBody > h2') | |
for (const heading of subheadings) { | |
const headingSlug = slug(heading.textContent) | |
heading.id = headingSlug | |
heading.insertAdjacentHTML('afterbegin', ` | |
<a href="#${headingSlug}" class="jump-to-anchor">${linkIcon}</a>` | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment