YUI Library Home

YUI Library Examples: Menu Family: Adding A Context Menu To A TreeView

Menu Family: Adding A Context Menu To A TreeView

This example demonstates how to use the ContextMenu widget to add a context menu to a YUI TreeView control. The context menu allows the user to add, edit and remove items from a TreeView instance.

Please Note: Opera users will need to do the following to use this example:

  • Opera for Windows: Hold down the control key and click with the left mouse button.
  • Opera for OS X: Hold down the command key (⌘) and click with the left mouse button.

When adding context menus to large data structures like a <table> or large list (<ol> or <ul>), it is recommended to bind a single YAHOO.widget.ContextMenu instance to the structure's root element, than to a set of its child nodes (<tr>s or <li>s). Doing so significantly improves the performance of a web page or application by reducing the number of "contextmenu" event handlers as well as the number of YAHOO.widget.ContextMenu instances in memory.

Begin by creating a TreeView instance. Next, create an object that maps HTML ids to their corresponding TextNode instances. As each TextNode instance is added to the TreeView, store a reference to it in the map.

Once the TreeView is created, instantiate a ContextMenu specifying the TreeView instance's root element as its trigger. Lastly, add a "triggerContextMenu" event handler for the ContextMenu instance that uses the "contextEventTarget" property to retrieve the TextNode instance that triggered its display. A reference to the TextNode is stored in a variable (oCurrentTextNode), so that it can be manipulated by the addNode, editNodeLabel, and deleteNode functions.

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

Menu Family Examples:

More Menu Family Resources:

Copyright © 2009 Yahoo! Inc. All rights reserved.

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