Simple, automated jumplinks with jQuery

You know those little hash links at the side of each heading on every blog post here at Assortment? This is how you can dynamically create them.

By Luke Whitehouse on

Building AssortmentJavaScript

Snippet

When developing Assortment I wanted a way for user's to easily link to certain sections of a post. They're a great addition to any blog and can really help to solidify the User Experience moving forward.

Whilst there are definitely options already available, I felt they were a little too robust for the solution I was looking for. In addition, as I'm writing all my posts in Markdown I needed a way to automate this, rather than rely on manually adding an ID to each heading, which Markdown doesn't support by default.

Here's the jQuery snippet I came up with:

/**
* Setup anchor links for headings in a content area
*/

// Get the content area to search through
var contentArea = $('.js-content-area');

// Check if the content area exists on page
if( contentArea.length ) {
  // Get all relevant headings within content area
  var headings = contentArea.find('h2, h3, h4');

  // For each heading found in content area
  headings.each(function(index) {
    // Store the current definition of 'this'
    var $this = $(this);

    // Convert heading text to slug format
    var headingText = convertToSlug($this.text());

    // assign slug to id
    $this.attr('id', headingText);

    // Create new anchor link within heading
    $this.prepend('<a href="#' + headingText + '" class="anchor"><span class="anchor__icon">#</span><span class="is-hidden">Get permalink</span></a>');
  });
}

// Sluggify a string
function convertToSlug(text) {
  var text = text.toLowerCase();
    text = text.replace(/[^\w ]+/g,'');
    text = text.replace(/ +/g,'-');

  return text;
}

I've also set this up as a Codepen demo for you to have a play around with.

http://codepen.io/_lukewh/pen/eBpdoo

Of course, theres much more you could do with this, including for starters setting this up as a jQuery plugin but this'll get you off the ground running.

Got a better idea? Let me know what solution you'd go for and why below!

Follow us on Twitter, Facebook or Github.
© Copyright 2019 Assortment.
Created and maintained by Luke Whitehouse.