For this tutorial we are going to work backwards then what we normally do. Let’s start by looking at the HTML we will be using since it is really simple, at least for now.
So far the HTML is just an unordered list with three entries. Two of these entries have a sub-list. This will be the base of our menu.
If we were to just put the code together like it is right now, the code would not work when the page was first loaded. The reason is because our sub-menus are not hidden to start with. That is where our style sheet becomes important. We will also need to add something to the main menu in order for the user to know that there are sub-menus. We can do this with a + sign, but we don’t want to add a plus sign to any menu that doesn’t have a sub-menu. To do these two things we will create to classes. Here is the CSS code.
The CSS is very simple for this example. If you wanted to make each sub-menu a different color to make it stand out a little, you can add that to the style sheet.
This code can be used for more then just a menu. Another way you can use this code is for a table of contents. Each sub-menu can have it’s own sub-menus. Adding the second level of sub-menus is very easy and allows the code to be scalable if needed. By using the code for a frequently asked questions page, it is really effective also. Each of the main menus can be a question or topic. Then each sub-menu can either be the answer or a question. If the sub-menus are questions a second level sub-menu can be added for answers. You can see the code in action here It shows examples of all three ways you can use the script as mentioned in this tutorial.