Step 3The JavaScript
First, we'll start off by writing a function to hide all of the menu items within our "subNav" container.
The below function gets a list of all UL elements within the subNav ID, then loops through that list and sets each element's display property to 'none'
function hideItems() { var list = document.getElementById("subNav").getElementsByTagName("ul"); for(i=0;i<list.length;i++) { list[i].style.display="none"; }}Alright, now let's start writing the function to display the sub-menu items.
function navMenu() { if (!document.getElementsByTagName){ return; } var anchors = document.getElementsByTagName('a');The first line of our function is a failsafe that simply tells the browser to follow the link if it doesn't support the 'getElementsByTagName' function.
The second line, similar to the function above, gets a list of all links and puts them into an array called 'anchors'
for (var i=0; i<anchors.length; i++){ var anchor = anchors[i]; var relAttribute = String(anchor.getAttribute('rel'));Now we start to loop through our 'anchors' array. Here, we grab the value of the 'rel' attribute for each link as we come to it.
if (relAttribute.toLowerCase().match('menutrigger')){ anchor.onclick = function() { Now we check to see if that 'rel' value (which we stored as 'relattribute') is equal to 'menutrigger' and if so, we're going to trigger our on-click event.
var nameAttribute = this.getAttribute('name') + "Nav"; var thismenu = document.getElementById(nameAttribute); hideItems(); thismenu.style.display="inline"; return false; } } }}First, we append the text 'Nav' to the end of the link's name attribute. Now our new nameAttribute value matches the name of the sub-nav menu we'll be affecting!
So then we grab that sub-menu and assign it to the 'thismenu' variable.
Now we hide all of our previously displayed sub-menus by calling the 'hideItems()' function we created earlier.
Then, we set the current sub-menu's display property to 'inline' to make it visible.
Finally, tell the browser not to follow the main menu link (that we just clicked) and close out all of our open brackets.
| « Previous Step | Download PDFView All Steps | Next Step » |
![]() |
Add Comment
|






































