Dynamic in-page navigation

Feed 1 posts, 1 voices

Avatar
0 posts

I wanted in-page navigation similar to what you see on Wikipedia: each HTML heading gets an anchor name, and a link to each appears at the top of the page.

I pieced together a script with JQuery 1.3.2 that pulls out heading tags (h3 and h4, in my case), generates a slug from the heading text, wraps each heading with an anchor, and generates a menu to insert in an element with ID “menu”.

$(document).ready(function() {
	var $menu = '';
	$("h3, h4").each(function () {
		$slug = $(this).text().replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'');
		$menu += '<li class="'+$(this)[0].nodeName.toLowerCase()+'"><a href="#' + $slug + '">' + $(this).text() + '</a></li>';
		$(this).wrap('<a name="' + $slug + '"></a>');
	});
	$("#menu").append("<ul>" + $menu + "</ul>");
});

I didn’t try to created nested lists for the different header levels; instead, each list element has a class (e.g. class=“h3”) that can be styled appropriately (e.g. margin-left:2em)

Here’s an example of the script in action.