Anchored Headings (Jump Links) with jQuery and CSS

Submitted by allan on Tue, 01/15/2013 - 23:34
I found this to be a problem recently when I built the documentation for the Views Natural Sort module. I always kinda envied the WordPress sites because they had this as an option to click on, but I had to code this for me. To give credit where it's due, this script was inspired over at Stack Overflow.

The JavaScript


jQuery(document).ready(function(){
  var usedHeadings = new Array();

  // I only wanted blog posts to be affected so i keep this to div.article-content.
   jQuery.each(jQuery(" h2, h3, h4", "div.article-content"), function(index, value) {
    var that = jQuery(this);
    var anchorName = that.text();

    // We want anchors to be unique, so if we have 2 headings that are the same...
    // add something to it.
    if (jQuery.inArray(anchorName, usedHeadings) != -1) {
      anchorName = anchorName + index;
    }
    usedHeadings.push(anchorName);
    
    // Wrap the heading text with the anchor tag and add a link so people
    // can save it if they wish to. The link (which shows up as a ΒΆ) appears 
    // only on hover over the title.
    jQuery(this).wrapInner('<a name="' + anchorName + '" />').hover(function(){       
      jQuery("a.heading-perm-link", this).show();
    },function(){
      jQuery("a.heading-perm-link", this).hide();
    }).append('<a class="heading-perm-link" href="#' + anchorName + '">&#182;');
  });
});

The CSS


/* Make the Jump Link hidden by default. */
a.heading-perm-link {
  display: none;
}

Final Thoughts

Feel free to use this in your Drupal site... or site in general as this isn't really Drupal specific. Also remember to extend the current theme you are using so that you can put this in your own JS file instead of overloading a contributed theme. For instance, I've extended FooTheme for this site.