YUI Library Home

YUI Library Examples: Menu Family: Basic Menu From JavaScript

Menu Family: Basic Menu From JavaScript

This example demonstrates how to create a Menu instance using nothing but JavaScript.

Note: By default clicking outside of a Menu instance will hide it. Additionally, MenuItem instances without a submenu or a URL to navigate to will hide their parent Menu instance when clicked. Click the "Show Menu" button below to make the Menu instance visible if it is hidden.

Creating a Menu from JavaScript

To create a Menu with no pre-existing markup on the page, call the Menu constructor (YAHOO.widget.Menu) passing the id of the Menu element to be created as the first argument.

Add items to a Menu instance via the addItem, insertItem, or addItems methods.

Finally, it is necessary to call the render method passing the id of, or reference to the element the Menu should be appended to.

1/*
2     Instantiate a Menu:  The first argument passed to the 
3     constructor is the id of the element in the page 
4     representing the Menu; the second is an object literal 
5     of configuration properties.
6*/ 
7 
8var oMenu = new YAHOO.widget.Menu("basicmenu", { fixedcenter: true }); 
9 
10 
11/*
12    Add items to the Menu instance by passing an array of object literals 
13    (each of which represents a set of YAHOO.widget.MenuItem 
14    configuration properties) to the "addItems" method.
15*/ 
16 
17oMenu.addItems([ 
18 
19        { text: "Yahoo! Mail", url: "http://mail.yahoo.com" }, 
20        { text: "Yahoo! Address Book", url: "http://addressbook.yahoo.com" }, 
21        { text: "Yahoo! Calendar", url: "http://calendar.yahoo.com" }, 
22        { text: "Yahoo! Notepad",  url: "http://notepad.yahoo.com" } 
23 
24    ]); 
25 
26 
27/*
28    Since this Menu instance is built completely from script, call the 
29    "render" method passing in the DOM element that it should be 
30    appended to.
31*/ 
32 
33oMenu.render("rendertarget"); 
view plain | print | ?

Menu Family Examples:

More Menu Family Resources:

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings