1. |
var allLinks = document.getElements ByTagName("a");
When the page loads, the initAll() function is called, and it begins by creating an array of all the links on the page.
|
2. |
for (var i=0;i<allLinks.length;i++) {
if (allLinks[i].className. indexOf("menuLink") > -1) {
allLinks[i].onclick = toggleMenu;
}
}
Once we have all the links, we loop through them, looking for those links with a class of menuLink and adding an onclick handler to just those links. Here, that onclick handler is set to call the toggleMenu() function when they're clicked.
|
3. |
var startMenu = this.href. lastIndexOf("/")+1;
var stopMenu = this.href. lastIndexOf(".");
Inside toggleMenu(), JavaScript has passed us this. Here, this is the link object that the user clicked, which means that this.href is the full link URL. But we only want the part between the last forward slash and the last period (that is, if the link was to http://www.javascriptworld.com/index.html, we'd only want "index"), so we create and set startMenu and stopMenu to be the locations in this.href where we want to start and stop finding the string that will end up being our menu name.
|
| |
4. |
var thisMenuName = this.href. substring(startMenu,stopMenu);
The menu name we want is between those two positions, so here's where we set it.
|
5. |
var thisMenu = document. getElementById (thisMenuName). style;
The variable thisMenu is set to a reference to the desired menu using the getElementById() method.
|
6. |
thisMenu.display = (thisMenu.display == "block") ? "none" : "block";
If the display property of thisMenu is block, then this code changes it to none. Alternatively, if it's none, it's changed to block. This is what toggles the menu display, as shown in Figures 14.1 and 14.2.
|
7. |
And finally, we return a value of falsethat's because the toggleMenu() function was called due to an onclick event handler on a link. When we return false, the href attribute never gets loaded into the browser window, so the viewer stays on the same page.
|