Home » Projects » Javascript menu

Javascript Menu

This is a small example on how to make a lean & mean javascript menu.

Look at vanbrug.org to see this menu in action. The script looks like this:


  function showm(ob, J) {
    for (i=0; i<Main.length; i+=3) { document.all(Main[i]).className="unfocus"; }
    ob.className="dofocus";
    for (s="", i=0; i < M[J].length; i+=2) {
      s += "<a class=unfocus href='" + M[J][i] + "'> " + M[J][i+1] +" </a>";
    }
    document.all("submenu").innerHTML=s+(i<2?" ":"");
  }

  function showmain() {
    for (s="", i=0, j=1; i < Main.length; i+=3, j++) {
      s += "<a class=unfocus onmouseover='showm(this," + j + ")' id='" + 
            Main[i] + "' href='" + Main[i+1] + "'> " + Main[i+2] +" </a>";
    }
    document.all("topmenu").innerHTML=s;
  }

After that, we define an array for the main- and submenus:


  Main=new Array(
    "l1", "http://google.com", "Google",
    "l2", "http://tldp.org", "LinuxDOCS", 
  );
  
  M=new Array();
  M[1]=new Array(
    "http://gmail.com","Gmail",
    "http://google.com/imghp", "Google Images",
  )
  M[2]=new Array();

To make sure the script shows the first menus, the 'onload' event in the body is used:


  <BODY onload='showmain();showm(document.all("l1"),1);';>

And to place the menus somewhere on the page, two 'span's are created:


  <span class=menu id=topmenu></span><br>
  <span class=menu id=submenu></span>

Finally, we create a stylesheet with two classes 'dofocus' and 'unfocus' to define the buttons in the menu:


  .dofocus .unfocus:hover { 
    height: 1.18em;
    line-height: 1.1em;
    float: left;
    width: 6em;
    background:blue url("/include/but-on.gif");
    text-align: center;
    text-decoration: none;
    color:yellow;
  }
  .unfocus {
    background:green url("/include/but-off.gif");
    color:white;
    height: 1.18em;
    line-height: 1.1em;
    float: left;
    width: 6em;
    text-align: center;
    text-decoration: none;
  }

And that's it. No superfluous, much too complicated layovers, hidden divs, java applets or what not, and still a nice and fast menu.