I got a request from a client for a 'mini' navigation menu to appear on
a page to allow the user to 'jump' to the various sections of the
page. Maintaining a set of named anchor hyperlinks in a document (with
a javascript-based select menu) is not really an option for someone who
doesn't know HTML, which is most people who use content management. In
the wrong hands this creates more trouble than it's worth.
so i
started thinking. the documents in question are well structured, using
paragraphs and headings, as enforced by the content management system.
i worked out this solution which is exactly what i need, a maintenance
free javascript jump menu, that doesn't add clutter to the document
with named anchors. it assumes that the all H2 tags should be
displayed as links in the menu. the javascript iterates through the H2
tags and loads up the menu, with a ScrollTo function used when an item
is selected.
here's a
screenshot

The code for the HTML page:
<script src="/JumpMenu.js" type="text/javascript"></script>
<select id="jumpNavSelect" name="jumpNavSelect" onchange="JumpToHeading(this.selectedIndex)">
<option value="">On this page...</option>
</select>
and the JumpMenu.js file
var array;
function CreateAnchorMenu() {
array = document.getElementsByTagName("h2");
var src = document.getElementById('jumpNavSelect');
// iterate through all H2 headings, add dropdown items for each.
for (var i = 0; i < array.length; i++) {
var heading = array[i];
var text = heading.firstChild.nodeValue;
if (!text)
continue;
src[i+1] = new Option(text, i);
}
}
function JumpToHeading(HeadingIndex) {
if (HeadingIndex == 0)
return;
var heading = array[HeadingIndex-1];
ScrollToElement(heading);
}
function ScrollToElement(theElement) {
var selectedPosX = 0;
var selectedPosY = 0;
while (theElement != null) {
selectedPosX += theElement.offsetLeft;
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
window.scrollTo(selectedPosX, selectedPosY);
}
window.onload = CreateAnchorMenu;