Using the YUI Menu Control - Rendering and Displaying the Menu
(Page 3 of 4 )
All we need to do now is add a little more JavaScript to render and display the menu. Add the following code to the bottom of the <head> section:
<script type="text/javascript">
YAHOO.util.init = function() {
var myMenu = new YAHOO.widget.Menu("mymenu");
myMenu.render();
myMenu.show();
};
YAHOO.util.Event.onAvailable("mymenu", YAHOO.util.init);
</script>
The YAHOO.util.init function contains the code that generates the menu. First a variable is created that holds an instance of the YAHOO.widget.Menu widget, taking the name you gave to the root div of the menu as an argument. It then calls the .render and .show methods to create and display the menu.
Built-in events are continually firing when YUI utilities and controls are active in a browser (even if they don't appear to be actually doing anything). The custom onAvailable event will fire once the <div> set as the root of the menu has been added to the DOM (i.e. has been rendered on-screen). As soon as the element is available, its event is picked up by YAHOO.util.Event and the constructor function that creates the menu is called, generating the menu on the page. This is everything the basic menu needs to function, so if you view it in your browse, you'll see it in all its glory!
Adding sub-menus to the menu is equally as straightforward; you just have to add a new menu (including the root and container <div> elements) to the <li> element that the sub-menu should appear under (make sure it appears before the closing </li> tag of the item the sub-menu is for). So to add a sub-menu to the About Us item, add the following code to the page:
<li class="yuimenuitem"><a rel="nofollow" target="_blank" href = "aboutus.htm">About Us</a>
<div id="aboutus" class="yuimenu">
<div class="bd">
<ul>
<li class="yuimenuitem"><a rel="nofollow" target="_blank" href = "philosophy.htm">Our Philosophy</a></li>
<li class="yuimenuitem"><a rel="nofollow" target="_blank" href = "contactus.htm">Contact Us</a></li>
<li class="yuimenuitem"><a rel="nofollow" target="_blank" href = "press.htm">Press Releases</a></li>
</ul>
</div>
</div>
</li>
The menu control will add the sub-menu and the default behavior (opening and closing the submenu when appropriate) to your menu, as well as adding the arrow icon indicating there is a sub menu. It should now look a little like the below screen shot:

Next: Changing the Styling >>
More JavaScript Articles
More By Dan Wellman