We’ve all seen those slick documentations and reference guides with anchor links next to each header. Although there are a couple scripts out there to handle this, they all seem to be a little much for the job, so we made a couple quick and easy snippets that you can use.

The basic version is like this:

$(document).ready(function() {
  $('h2').each(function(index) {
    $(this).attr('id', 'section' + index);
    $(this).prepend('<a href="#section' + index + '">#</a> ');
  });
});

See the Pen Auto anchor headings example 1 by flyingfisch (@flyingfisch) on CodePen.

This adds id’s to all your h2 tags and then it adds the anchor links. The result looks like this:

See the Pen Auto anchor headings example 1 by flyingfisch (@flyingfisch) on CodePen.

Don’t want the pound sign at the beginning of the heading? Just use .append instead of .prepend. Want it to show only when the header is hovered? With a little jQuery and CSS we can do that too. As far as the CSS goes, the only important part is

a.hidden {
  display: none;
}

And the jQuery looks like this:

$(document).ready(function() {
  $('h2').each(function(index) {
    $(this).attr('id', 'section' + index);
    $(this).append(' <a class="anchor hidden" href="#section' + index + '">#</a>');
  });
  $('h2').mouseover(function() {
    $(this).find('.hidden').removeClass('hidden');
  });
  $('h2').mouseout(function() {
    $(this).find('a.anchor').addClass('hidden');
  });
});

See the Pen Auto anchor headings example 2 by flyingfisch (@flyingfisch) on CodePen.

The result looks like this:

See the Pen Auto anchor headings example 2 by flyingfisch (@flyingfisch) on CodePen.

Lastly, if you need a table of contents, here is the javascript:

$(document).ready(function() {
  $('h2').each(function(index) {
    $(this).attr('id', 'section' + index);
    $(this).append(' <a class="anchor hidden" href="#section' + index + '">#</a>');
    $('#toc ol').append('<li><a href="#section' + index + '">' + $(this).html() + '</a></li>');
  });
  
  $('h2').mouseover(function() {
    $(this).find('.hidden').removeClass('hidden');
  });
  $('h2').mouseout(function() {
    $(this).find('a.anchor').addClass('hidden');
  });
});

See the Pen Auto anchor headings example 3 by flyingfisch (@flyingfisch) on CodePen.

Note that the HTML was also changed slightly: we now have a div with the toc id and a <ol> element inside.

Here is the result:

See the Pen Auto anchor headings example 3 by flyingfisch (@flyingfisch) on CodePen.

Serve cached, edit to taste.

About Mark Fischer, Jr.

Mark is a web developer and programmer. He likes reading classic novels, listening to classical music, skiing, and eating donuts.

Filed under jquery, tutorial