Search code examples
jekyllgithub-pageskramdown

How do I add permalinks to headers in kramdown?


I'm building a website with Jekyll and Github-Page written in markdown. I want to make it easy to permalink to headers, the way most online documentation does.

I want to get a URL with a hash when I click on a header. Is there an easy way to achieve this in Kramdown or in Jekyll's config?

Markdown page

#### A regular header

A regular sentence.

Ideal result

<h4 id="a-regular-header"><a href="#a-regular-header">A regular header</a></h4>
<p>A regular sentence.</p>

Solution

  • You can do this manually in the Markdown for each title:

    #### [A regular header](#a-regular-header)
    
    A regular sentence.
    

    The downside there is the maintenance cost. Another option would be to create the links on the client side by adding this to the bottom of your chosen pages:

    <script>
        var headings = document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]");
    
        for (var i = 0; i < headings.length; i++) {
            headings[i].innerHTML =
                '<a href="#' + headings[i].id + '">' +
                    headings[i].innerText +
                '</a>';
        }
    </script>
    

    You could look into a plugin, modified Markdown parser or task runner like gulp.js to do this at build time if the JavaScript dependency doesn't suit your audience. You can't use these alternatives if you want GitHub Pages to build your page, but you can build locally and commit the output.