Home Page -> DOM Tutorials -> Using Events -> Implementing showMenu()

Implementing showMenu()

All that remains now is to implement the showMenu() function, which is shown below. The line numbers are only for reference.

 1 function showMenu( evt )
 2 {
 3     var owner = findOwner( evt );
 4 
 5     var divNum;
 6 
 7     divNum = owner.attributes.getNamedItem("id").nodeValue;
 8 
 9     divNum = parseInt( divNum.substr(1) );
10 
11     if (getIdProperty( "s" + divNum, "display") != "block" )
12     {
13         setIdProperty("s" + divNum, "display", "block");
14         document.images["i" + divNum].src = "../minus.png";
15     }
16     else
17     {
18         setIdProperty("s" + divNum, "display", "none");
19         document.images["i" + divNum].src = "../plus.png";
20     }
21 }

Here are the lines of interest:

Line 3
As in the highlight() and dim() functions, we first have to find the “owner” of the click event.
Line 7
A node's attributes property gives a list of all the tag's attribute=value pairs. It's indexed by string, so we need to use the getNamedItem() method to find the id attribute's value (given by the nodeValue property).
Line 9
Since we've cleverly named all the <div> tags with ids like m0, m1, etc., we use the substr method to extract the digit.
Line 11
Checks to see if a submenu is already displayed by looking at its display property.
Lines 13-14, 18-19
We've also numbered the ids of the submenus and the images, so it's easy to change their properties and image sources.

  Finding the div  Index Summary