Adding anchor next to headers


#1

Some websites, including all rendered Markdown documents on Github, have a small “anchor” next to each headline if you hover over it. They are directs links to a specific header, like in this example from Github:

<h2>
<a id="user-content-overview" class="anchor" href="#overview" aria-hidden="true">
<span class="octicon octicon-link"></span></a>Overview
</h2>

Is it possible to add them next each headline during the rendering process?


[SOLVED] Anchor image for headers
#2

You should check the Blackfriday and MMark doc. Probably not.


#3

The README of Blackfriday listed indeed an external tool to do that and which could be integrated into hugo as an option.


#4

We already do GitHub style highlighting, so I don’t think we’re gonna include an external lib just to get the header linking going.


#5

It was just an idea.


#6

I like this idea and it turns out that it requires no core changes at all. Apparently hugo is already adding an id to every header on each page, so all you need is a link to them. A ghetto, poorly styled option would simply be:

$('h2').each(function() { $(this).prepend('<a href=#' + $(this).context.id + '>🔗 </a>') })

Of course you’d need to do that for all of h1 through h5 (or whatever.) But it works and requires no extra libraries or anything. I hope to make it styled like other things where the link is invisible unless you hover over it and it’s to the left of the header.


#7

Thanks. I needed a version without jQuery so here it is:

<script>
function addAnchor(element) {
  element.innerHTML = `<a href="#${element.id}">${element.innerText}</a>`
}

 document.addEventListener('DOMContentLoaded', function () {
  var headers = document.querySelectorAll('article h2')
  if (headers) {
    headers.forEach(addAnchor)
  }
})
</script>

#8

AnchorJS can be used to do this.


#9

Being JS-illiterate, I just use this one-liner in Hugo partial :smiley:

Use it as:

{{ partial "headline-hash.html" .Content }}

Example


Adding a link icon to headings
Adding a link icon to headings
#10

Slight variation to make it closer to a GitHub style:

.hanchor { font-size: 50%; visibility: hidden}
h2:hover a { visibility: visible}
function addAnchor(element) {
    element.insertAdjacentHTML('beforeend', `<a href="#${element.id}" class="hanchor" ariaLabel="Anchor">🔗</a>` )
}
document.addEventListener('DOMContentLoaded', function () {
    // Add anchor links to all headings
    var headers = document.querySelectorAll('article h1[id], article h2[id], article h3[id], article h4[id]')
    if (headers) {
        headers.forEach(addAnchor)
    }
 });

#11

Oh, and if you want to color that character something other than black, you will need to add the “variation selector” character after it.

	&#x1F517;&#xFE0E;

Will do it.

That’s because the link icon is treated as an emoji and they have their own colours, they don’t take the CSS text colour.