jQuery: inserting footnotes

When you have a text-based page, it's often useful to create some footnotes to be inserted at the bottom of your document. In this post I'm going to show you how to insert such footnotes with jQuery. Note, however, that this practice relies entirely on JavaScript and for that reason it's not recommended. If accessibility is one of the goals of your web site, you should not rely on this technique. Otherwise, you can use it.

Let's start by saying that we have a series of paragraphs which must have a link pointing to a footnote. The underlying structure to create is as follows:

<sup>
  <a href="#note-n">n</a>
</sup>

n is a progressive number, so we'll have note-1, note-2 and so on. Of course you have to create the elements these links point to as well. The structure is the following:

<ol>
  <li id="note-1">...</li>
  <li id="note-2">...</li>
  <!--more notes-->
</ol>

Here's the jQuery code:

$(document).ready(function() {

  $('<ol/>').appendTo('#notes');
  
  var index = 0;
  
  $('p').each(function() {
  
   index += 1;
    var $p = $(this);
    var note = '<sup><a href="#note-' +
               index + '">' + index +
               '</a></sup>';
               
    $(note).appendTo($p);
    
    var footnote = '<li id="note-' +
                    index + '">Note ' +
                    index + '</li>';
    $(footnote).appendTo('#notes ol'); 
    
  
  
  });


});

We use a progressive index to number our notes. You can see the result below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.