DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Javascript Footnote Creator

03.21.2008
| 5921 views |
  • submit to reddit
        Finds footnotes and adds them to a list. Just put "footnote" into the class of an element, and it'll automatically pull it out of context, replace it with a reference link, put the footnote into the list with id 'notes', and include a backreference so that your readers don't get lost. Embedded markup and nested footnotes work fine. Everything has CSS classes, so you can style it to your heart's content.

		<script src='prototype.js'>
			/*don't confuse IE; put content in empty script blocks*/
		</script>
		<script>
			var Footnote = Class.create({
				initialize: function(element) {
					var notes = this.findNotes();
					var number = notes.select('li').length + 1;
					
					var ref = document.createElement('a');
					ref.className = 'footnote-reference';
					ref.href = '#footnote-' + number;
					ref.id = 'reference-' + number;
					ref.appendChild(document.createTextNode(number));
					element.parentNode.insertBefore(ref, element);
					
					$(element).removeClassName('footnote')
					
					var li = document.createElement('li');
					li.className = 'footnote';
					li.id = 'footnote-' + number;
					li.appendChild(element);
					
					var backref = document.createElement('a');
					backref.className = 'footnote-backreference';
					backref.href = '#reference-' + number;
					backref.appendChild(document.createTextNode("\u21A9"));
					li.appendChild(document.createTextNode(" "));
					li.appendChild(backref)
					
					notes.appendChild(li);
				},
				findNotes: function() {
					return $('notes');
				}
			});
			
			Event.observe(window, 'load', function() {
				$$('.footnote').each(function(e) {new Footnote(e)});
			})
		</script>