In the previous part of this two-part tutorial, I began describing how to build a bulleted menu of links, such as you might see on many web sites. These links unfold, so that some headings, when clicked, reveal links below them to pages that are subcategories. In this second part, I will jump right back into the subject, starting with the JavaScript code we need to accomplish the magic.
Completing a Bulleted Menu Of Links (Page 1 of 5 )
The JavaScript Code
Each ID is made up of two parts: the left part, which is either LI or UL; and the right part, which is a number. When any LI element that is expandable is clicked, the function “splitID(ID)” is called. This function splits the ID into two parts, throwing away the underscore. The function is:
function splitID(ID)
{
IDPartsArr = ID.split("_");
//call the function to expand or collapse the unordered list
expandOrCollapse(IDPartsArr[0], IDPartsArr[1]);
}
When you click an expandable link, it calls the function, sending its ID as argument. JavaScript has a string method called split(separator). The method splits a string based on a separator and discards the separator. You use the method with the string function as follows:
stringObject.split(separator)
So, for example, if the string object is “LI_11,” the result will be two sub strings, which are “LI” and “11.” The underscore is discarded. In our example above, the ID is the string object. An array is returned by the JavaScript method. The elements of the array are the spitted sub strings. In our example, the array is held by the IDPartsArr variable. In our project, this array will always have two elements: the first one, “LI” or UL, and the second one, a number.
Lastly, this function calls another function, “expandOrCollapse().” The first argument of this function is the first element of the IDPartsArr array. The second argument of the function is the second element of the IDPartsArr array.