Bottom-clenchingly simple hierarchical Javascript menus

  1. Create your HTML as a set of divs, nested like so:

    DIV nested diagram, the system comprises a recursive set of divs of class node, each node keeps it's children within another div of class child

  2. Whack this in your stylesheet:

    .child { margin-left:15px; display:none; }

  3. 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.