Bottom-clenchingly simple hierarchical Javascript menus
-
Create your HTML as a set of divs, nested like so:
-
Whack this in your stylesheet:
.child { margin-left:15px; display:none; }
-
Stick the following function in the page and call it from onclick on every node that has children:
function selectNode(id) {
node = document.getElementById("child" + id);
if (node) {
if (node.open) {
node.style.display = "none";
document.images["node" + id].src = "closed.gif";
node.open = false;
}
else {
node.style.display = "block";
document.images["node" + id].src = "open.gif";
node.open = true;
}
}
}
The best bit is that sub trees remain open while hidden. To explain, imagine Blah and Blah 2 have been clicked and Blah 3 is visible. If you know click Blah you will hide Blahs 1, 2, 3 and 4. But if you click Blah again, Blah 3 will still be visible under Blah 2. You really have to see it in action, so here’s one I made earlier.