YUI Library Home

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

Menu Family: Adding A Context Menu To A Table

This example creates context menu for an HTML table and illustrates how the content of a ContextMenu instance can be replaced on the fly based on the element that triggered its display.

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 each 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 an <table> and giving <tr> elements that should have the same context menu a similar class name.

Next, use the onContentReady method of the Event utility to listen for when the <table> element is are ready to be scripted.

Inside the function passed to the Event Utility's onContentReady method, create a shortcut to the Dom Utility (since it will be used frequently) and an object literal that maps each class name to a set of MenuItem configuration properties.

Lastly, add a "triggerContextMenu" event handler to the ContextMenu instance. This event handler makes use of the "contextEventTarget" property to determine which <tr> element was the target of the "contextmenu" event. Once found, the <tr> element's class name is used to look up its corresponding menu items in the "oContextMenuItems" map, which are then added to the ContextMenu instance via the "addItems" method.

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 © 2011 Yahoo! Inc. All rights reserved.

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