Skip to content

Instantly share code, notes, and snippets.

@myobie
Last active January 16, 2020 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/36c5e7a6d21400df848e5c1ff6235d51 to your computer and use it in GitHub Desktop.
Save myobie/36c5e7a6d21400df848e5c1ff6235d51 to your computer and use it in GitHub Desktop.
Insert a link to the id of any heading which has an id
function linkHeadings () {
document.querySelectorAll('h2[id], h3[id], h4[id], h5[id], h6[id]').forEach(heading => {
const anchor = document.createElement('a')
anchor.innerText = '#'
anchor.classList.add('permalink')
anchor.setAttribute('href', `#${heading.id}`)
anchor.setAttribute('title', 'Permalink')
heading.append(anchor)
})
}
linkHeadings()
h2, h3, h4, h5, h6 {
position: relative;
}
/* By default, show the permalink at the end of the heading's content */
h2 > a.permalink,
h3 > a.permalink,
h4 > a.permalink,
h5 > a.permalink,
h6 > a.permalink {
text-decoration: none;
padding-left: 10px;
}
@media (hover: hover) {
/* For devices that can hover, show the permalink to the left of the heading on hover */
h2 > a.permalink,
h3 > a.permalink,
h4 > a.permalink,
h5 > a.permalink,
h6 > a.permalink {
display: none;
position: absolute;
bottom: 0;
right: 100%;
padding-right: 10px;
padding-left: 0;
text-decoration: none;
}
h2:hover > a.permalink,
h3:hover > a.permalink,
h4:hover > a.permalink,
h5:hover > a.permalink,
h6:hover > a.permalink {
display: block;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment