Add anchor links to the headers in my posts

This articles describes some JS that will automatically append a link SVG icon for headers in post content that have an id attribute.

SVG Elements and namespacing

The SVG namespace is not naturally entwined with HTML, so if you've ever tried to create an SVG element, you might have noticed it doesn't work using the standard document.createElement DOM API method.

SVG elements are namespaced under http://www.w3.org/2000/svg, so creating them needs to be done with the document.createElementNS DOM API.
document.createElementNS('http://www.w3.org/2000/svg', 'svg')
Similarly, the use elements for re-using an SVG definition defined using the xlink namespace.
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
use.setAttributeNS(
    'http://www.w3.org/1999/xlink',
    'xlink:href',
    '/responsive/sprite_v1_6.css.svg#ic_24_link_dark');

This example creates the Get link icon using the use element and xlink namespace.

The JS

The custom HTML gadget executes the following javascript to create the elements.
<script>
document.querySelectorAll('.Blog h2, .Blog h3, .Blog h4').forEach(
  h => {
    if (!h.id || h.querySelector('.anchor')) return;
    h.innerText = h.innerText + ' '; // Add some whitespace.
    var a = document.createElement('a');
    a.href = '#' + h.id;
    a.setAttribute('class', 'anchor');
    h.appendChild(a);
    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('class', 'svg-icon-24');
    a.appendChild(svg);
    var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
    use.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
    use.setAttributeNS(
        'http://www.w3.org/1999/xlink',
        'xlink:href',
        '/responsive/sprite_v1_6.css.svg#ic_24_link_dark');
    svg.appendChild(use);
  });
  </script>

Comments

Popular posts from this blog

Filter out certain labels from my Blog Homepage

Change the landing page of my blog

Get Facebook to show feature image for your Blog's Homepage