Class: ojMenu

Oracle® JavaScript Extension Toolkit (JET)
1.2.0

E65435-01

QuickNav

Options

oj. ojMenu extends oj.baseComponent

Version:
  • 1.2.0
Since:
  • 0.6

Description: Themeable, WAI-ARIA-compliant popup menu with mouse and keyboard interactions for navigation.

A JET Menu can be created from any valid markup as long as the elements have a strict parent/child relationship and each menu item has an anchor. The most commonly used element is the unordered list ( <ul> ):

<ul id="menu" style="display:none" aria-label="Order Edit">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a></li>
  <li><a href="#">Item 3</a>
    <ul>
      <li><a href="#">Item 3-1</a></li>
      <li><a href="#">Item 3-2</a></li>
      <li><a href="#">Item 3-3</a></li>
      <li><a href="#">Item 3-4</a></li>
      <li><a href="#">Item 3-5</a></li>
    </ul>
  </li>
  <li><a href="#">Item 4</a></li>
  <li><a href="#">Item 5</a></li>
</ul>

If you use a structure other than <ul>/<li>, including using the same element for the menu and the menu items, use the menuSelector option to specify a way to differentiate the two elements, e.g., menuSelector: "div.menuElement".

Any menu item can be disabled by adding the oj-disabled class to that element. As with any DOM change, doing so post-init requires a refresh() of the component.

JET Menus are not intended to be scrollable, as large, unwieldy menus are not good UX. Ideally menus should have a manageable number of items; if this is not possible, then it is preferable to organize contents into submenus, rather than introducing scrolling.

JET Menu is a popup component, for use with context menu, menu button, or similar functionality. It is not intended to sit inline on the page. See also the JET NavigationList component.

For this reason, the component is automatically hidden until it is opened. However, this styling is not applied until the component is initialized. To avoid a FOUC (flash of unstyled content), applications are encouraged to apply style="display:none" to the menu markup, as shown in the above code sample.

Icons

Submenu icons are inserted automatically. To add other icons to menu items, include them in the markup and include the oj-menu-item-icon class, as follows:

<ul id="menu" style="display:none" aria-label="Order Edit">
  <li id="foo"><a href="#"><span class="oj-menu-item-icon demo-icon-font demo-palette-icon-24"></span>Foo</a></li>
</ul>

Dividers

Divider elements can be created by including unlinked menu items that contain only spaces and/or dashes, or nothing at all:

<ul id="menu" style="display:none" aria-label="Order Edit">
  <li><a href="#">Item 1</a></li>
  <li>---</li>
  <li><a href="#">Item 2</a></li>
</ul>

For WAI-ARIA compliance, JET automatically adds role="separator" to the divider element.

Touch End User Information

Target Gesture Action
Menu Item Tap Invoke the menu item's action, which may be opening a submenu.
JET Component or HTML Element having a JET Context Menu Press & Hold Open the context menu.
Elsewhere on Page Touch Close the menu.

Disabled items do not allow any touch interaction.

Keyboard End User Information

Target Key Action
Menu Item Enter or Space Invoke the focused menu item's action, which may be opening a submenu.
UpArrow Move focus to the previous menu item, wrapping around at the top.
DownArrow Move focus to the next menu item, wrapping around at the bottom.
Home Move focus to the first menu item.
End Move focus to the last menu item.
RightArrow (LeftArrow in RTL*) Open the submenu, if any.
Menu Item in Top-level Menu Esc Close the menu and move focus to the launcher.
Menu Item in Submenu Esc or LeftArrow (RightArrow in RTL*) Close the submenu and move focus to the parent menu item.
JET Component or HTML Element having a JET Context Menu Shift + F10 Open the context menu.

* RTL refers to pages written in a right-to-left language such as Arabic.

Typing a letter moves focus to the first item whose title starts with that character. Repeating the same character cycles through matching items. Typing more characters within the one second timer matches those characters.

Note that the "Search for text when I start typing" feature in Firefox can interfere with web content that accepts keystrokes, such as this "type a letter" feature of JET Menu.

Disabled items can receive keyboard focus, but do not allow any other interaction.

Accessibility

The app should supply either an aria-label or aria-labelledby attribute on the menu's root element, except possibly for menu buttons as discussed below. These attributes should not be supplied for submenus, which are labeled automatically.

If a menu is shared by different launchers, and should have a different label for each launcher, then a beforeOpen listener can be used to set a different label per launch.

For a menu launched exclusively by one or more menu buttons, these attributes are optional. When the menu is opened via the menu button UI, if neither attribute is present after all beforeOpen listeners have been called, then aria-labelledby will be set on the menu, referencing the menu button, and will be removed when the menu is closed. This approach provides a useful default label, while allowing the app to supply a different label if desired, and while allowing the menu to be shared by several menu buttons and/or other launchers.

Disabled content: JET supports an accessible luminosity contrast ratio, as specified in WCAG 2.0 - Section 1.4.3 "Contrast", in the themes that are accessible. (See the "Theming" chapter of the JET Developer Guide for more information on which themes are accessible.) Note that Section 1.4.3 says that text or images of text that are part of an inactive user interface component have no contrast requirement. Because disabled content may not meet the minimum contrast ratio required of enabled content, it cannot be used to convey meaningful information.

Styling

Class Description
oj-disabled Disables a menu item. See the Overview for details.
oj-menu-item-icon Required when adding an icon to a menu item. See Icons for details.

Reparenting

When a menu is opened, it will be reparented in the document and reparented back when closed. The goal of this design is to maintain as much of the page author's document structure as possible, while avoiding most of the clipping and positioning issues of a completely inline design.

If opened from another popup, the menu will be reparented to the nearest parent popup. Otherwise, the menu will be reparented to a container in the document body.

The context of opening is defined by the resolved openOptions.launcher value, which can be set via the option, via the argument to the open() method, or via a beforeOpen listener.

All menus are assigned the same z-index values. The layering between peer popups reflects the opening order. In addition, the page author has control over z-index weights by way of the menu's layer. The menu's layer defines the "stacking context" and assignd the "oj-menu-layer" style.

Some notable consequences of this design:

  • Events raised within the menu will not bubble up to the menu's original ancestors. Instead, listeners for menu events should be applied to either the menu's root element, or the document.
  • Likewise, developers should not use CSS descendant selectors, or similar logic, that assumes that the menu will remain a child of its original parent.

Performance

If a menu launcher (such as a menu button or item with a context menu) is stamped inside a table, dataGrid, or other container, the resulting set of launchers should share a single menu defined outside the table or dataGrid.

Reading direction

The only supported way to set the reading direction (LTR or RTL) is to set the "dir" attribute on the <html> element of the page. As with any JET component, in the unusual case that the reading direction is changed post-init, the menu must be refresh()ed, or the page must be reloaded.

Pseudo-selectors

The :oj-menu pseudo-selector can be used in jQuery expressions to select JET Menus. For example:

$( ":oj-menu" ) // selects all JET Menus on the page
$myEventTarget.closest( ":oj-menu" ) // selects the closest ancestor that is a JET Menu

Declarative Binding

For components like Menu and Buttonset that contain a number of like items, applications may wish to use a foreach Knockout binding to stamp out the contents. This binding cannot live on the same node as the JET ojComponent binding, and must instead live on a nested virtual element as follows:

<ul id="menu" style="display:none" aria-label="Order Edit" data-bind="ojComponent: {component: 'ojMenu'}">
    <!-- ko foreach: menuItems -->
        <li data-bind="attr: {id: id}, css: {'oj-disabled': disabled}">
            <a href="#" data-bind="text: label"></a>
        </li>
    <!-- /ko -->
</ul>

JET for jQuery UI developers

  1. All JQUI and JET components inherit disable() and enable() methods from the base class. This API duplicates the functionality of the disabled option. In JET, to keep the API as lean as possible, we have chosen not to document these methods outside of this section.
  2. JET Menus are popup menus, and are not intended to sit statically on the page.
  3. For clarity, JQUI Menu's menus option has been renamed to menuSelector in JET Menu.
  4. JQUI Menu's position option is now a field of the submenuOpenOptions option in JET Menu.
  5. JQUI Menu has a role option, which defaults to "menu". This option was removed in JET Menu. Reason: JET Menu is a menu component; thus we feel that the only appropriate WAI-ARIA role for our component is "menu".
  6. JQUI Menu has isFirstItem() and isLastItem() methods, which were removed in JET Menu. Reason: To keep the API lean, we prefer to avoid methods with such specific functionality.
  7. JQUI Menu has a number of "programmatic navigation" methods, and focus / blur events, that were removed in JET Menu due to lack of a use case.
  8. JET Menu swaps the functionality of the left and right arrow keys in RTL.
  9. JET Menu creates WAI-ARIA compliant separator elements, by applying role="separator" to them.

Also, event names for all JET components are prefixed with "oj", instead of component-specific prefixes like "menu" or "button". E.g. the JQUI menucreate event is ojcreate in JET, as shown in the doc for that event. Reason: This makes the API more powerful. It allows apps to listen to "foo" events from all JET components via:

$( document ).on( "ojfoo", myFunc);
or to "foo" events only from JET Menus (the JQUI functionality) via:
$( document ).on( "ojfoo", ":oj-menu", myFunc);

Initializer

.ojMenu(options)

Creates a JET Menu.
Parameters:
Name Type Argument Description
options Object <optional>
a map of option-value pairs to set on the component
Source:
Examples

Initialize the menu with no options specified:

$( ".selector" ).ojMenu();

Initialize the menu with some options and callbacks specified:

$( ".selector" ).ojMenu( { "disabled": true, "create": function( event, ui ) {} } );

Initialize the menu via the JET ojComponent binding:

<ul id="menu" style="display:none" aria-label="Order Edit" 
    data-bind="ojComponent: { component: 'ojMenu',
                              disabled: true,
                              select: menuItemSelect }">

Options

contextMenu :Object

JQ selector identifying the JET Menu that the component should launch as a context menu on right-click, Shift-F10, Press & Hold, or component-specific gesture. If specified, the browser's native context menu will be replaced by the specified JET Menu.

To specify a JET context menu on a DOM element that is not a JET component, see the ojContextMenu binding.

To make the page semantically accurate from the outset, applications are encouraged to specify the context menu via the standard HTML5 syntax shown in the below example. When the component is initialized, the context menu thus specified will be set on the component.

After create time, the contextMenu option should be set via this API, not by setting the DOM attribute.

Default Value:
  • null
Inherited From:
Source:
Examples

Initialize a JET component with a context menu:

// via recommended HTML5 syntax:
<div id="myComponent" contextmenu="myMenu" data-bind="ojComponent: { ... }>

// via JET initializer (less preferred) :
// Foo is the component, e.g., InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo({ "contextMenu": "#myMenu" });

Get or set the contextMenu option, after initialization:

// getter
// Foo is the component, e.g., InputText, InputNumber, Select, etc.
var menu = $( ".selector" ).ojFoo( "option", "contextMenu" );

// setter
// Foo is the component, e.g., InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo( "option", "contextMenu", ".my-marker-class" );

Set a JET context menu on an ordinary HTML element:

<a href="#" id="myAnchor" contextmenu="myMenu" data-bind="ojContextMenu: {}">Some text

disabled :boolean

Disables the menu if set to true.
Default Value:
  • false
Source:
Examples

Initialize the menu with the disabled option specified:

$( ".selector" ).ojMenu( { "disabled": true } );

Get or set the disabled option, after initialization:

// getter
var disabled = $( ".selector" ).ojMenu( "option", "disabled" );

// setter
$( ".selector" ).ojMenu( "option", "disabled", true );
Selector for the elements that serve as the menu container, including submenus.

Note: The menuSelector option should not be changed after initialization. Existing submenus will not be updated.

Default Value:
  • "ul"
Source:
Examples

Initialize the menu with the menuSelector option specified:

$( ".selector" ).ojMenu({ menuSelector: "div" });

Get the menuSelector option, after initialization:

// getter
var menuSelector = $( ".selector" ).ojMenu( "option", "menuSelector" );

openOptions :Object

A collection of settings impacting the launch of a popup menu. These openOptions may be accessed and overridden individually or collectively, as seen in the examples.

This option affects the top-level menu, while submenuOpenOptions affects submenus.

The values set here can be overridden on a per-launch basis by passing the corresponding params into the open method. Those per-launch values can be further customized by a beforeOpen listener.

The built-in menu button and context menu functionality overrides some of the Menu's openOptions, for WAI-ARIA compliance and other reasons. Thus, if the app really wants to customize those values, it must do so in a beforeOpen listener. If the built-in menu button or context menu functionality is modified in this way, it is the app's responsibility to ensure that the result is both correct and accessible.

Source:
Examples

Initialize the menu, setting some openOptions. This syntax leaves the other openOptions intact at create time, but not if called after create time:

$( ".selector" ).ojMenu({ openOptions: { "initialFocus": "none", "launcher": "#myLauncher" } });

Get or set the openOptions option, after initialization:

// Get one
var value = $( ".selector" ).ojMenu( "option", "openOptions.launcher" );

// Get all
var values = $( ".selector" ).ojMenu( "option", "openOptions" );

// Set one, leaving the others intact
$( ".selector" ).ojMenu( "option", "openOptions.initialFocus", "none" );

// Set many.  Any existing openOptions not listed are lost
$( ".selector" ).ojMenu( "option", "openOptions", { launcher: "#myLauncher",
                                                    initialFocus: "firstItem",
                                                    position: myPositionObj } );

openOptions.initialFocus :string

Determines focus behavior when the popup menu is initially opened.
Supported Values:
Name Type Description
"none" string Leaves focus where it is, e.g. on the launching component.
"menu" string Focuses the menu itself, with no menu item focused (e.g. typical Context Menu behavior).
"firstItem": string Focuses the first menu item (e.g. MenuButton DownArrow behavior).
Default Value:
  • "menu"
Source:
Examples

Initialize the menu with the openOptions.initialFocus sub-option specified:

$( ".selector" ).ojMenu({ openOptions: { initialFocus: "firstItem" } });

Get or set the openOptions.initialFocus sub-option, after initialization:

// getter
var initialFocus = $( ".selector" ).ojMenu( "option", "openOptions.initialFocus" );

// setter:
$( ".selector" ).ojMenu( "option", "openOptions.initialFocus", "none" );

openOptions.launcher :string|jQuery

The DOM node (which may or may not be a JET component) that launches this popup menu. This node must be focusable, as focus is returned to it upon menu dismissal.

Can be a string JQ selector indicating the DOM node, or a jQuery object containing the node.

The launcher must either be specified in this component option, or on each menu launch -- see open() and beforeOpen.

Default Value:
  • null
Source:
Examples

Initialize the menu with the openOptions.launcher sub-option specified:

$( ".selector" ).ojMenu({ openOptions: { launcher: "#myLauncher" } });

Get or set the openOptions.launcher sub-option, after initialization:

// getter
var launcher = $( ".selector" ).ojMenu( "option", "openOptions.launcher" );

// setter:
$( ".selector" ).ojMenu( "option", "openOptions.launcher", "#myLauncher" );

openOptions.position :Object

Determines the position of this menu when launched via the open() method or via menu button or context menu functionality.

Please refer to the jQuery UI Position utility for details about the various choices. In addition to that syntax, note that JET supports the following reading direction-aware extended syntax in the my and at fields:

  • JET supports start and end values wherever left and right are supported. The start value means "left in LTR; right in RTL", while the end value means "right in LTR; left in RTL."
  • Similarly, JET supports > and < operators wherever + and - are supported. The > value means "+ in LTR; - in RTL", while the < value means "- in LTR; + in RTL." E.g. a my value of "start>40" shifts the menu 40px "endward," while a my value of "start<40" shifts the menu 40px "startward."

Menu also supports the following extended syntax for the of field:

  • The "event" keyword means "position the menu relative to the UI event that opened the menu."
  • The "launcher" keyword means "position the menu relative to the launcher element."

By default, when the of field is not set, the menu is positioned relative to the launcher.

Default Value:
  • { "my": "start top", "at": "start bottom", "collision": "flipfit" }
Source:
Examples

Initialize the menu with the openOptions.position option specified:

$( ".selector" ).ojMenu({ openOptions: { 
    position: { "my": "start top", "at": "end<5 top+5", "collision": "flipfit" } 
} });

Get or set the openOptions.position sub-option, after initialization:

// Get one field of position object
var position = $( ".selector" ).ojMenu( "option", "openOptions.position.my" );

// Get entire position object
var position = $( ".selector" ).ojMenu( "option", "openOptions.position" );

// Set one field of position object, leaving the others intact
$( ".selector" ).ojMenu( "option", "openOptions.position.at", "end bottom" );

// Set entire position object. Any fields not listed are lost.
$( ".selector" ).ojMenu( "option", "openOptions.position", { 
    "my": "start top", "at": "end<5 top+5", "collision": "flipfit" 
} );

rootAttributes :Object

Attributes specified here will be set on the component's root DOM element at creation time. This is particularly useful for components like Dialog that wrap themselves in a new root element at creation time.

The supported attributes are id, which overwrites any existing value, and class and style, which are appended to the current class and style, if any.

Setting this option after component creation has no effect. At that time, the root element already exists, and can be accessed directly via the widget method, per the second example below.

Default Value:
  • null
Inherited From:
Source:
Examples

Initialize a JET component, specifying a set of attributes to be set on the component's root DOM element:

// Foo is the component, e.g., Menu, Button, InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo({ "rootAttributes": {
  "id": "myId",
  "style": "max-width:100%; color:blue;",
  "class": "my-class"
}});

After initialization, rootAttributes should not be used. It is not needed at that time, as attributes of the root DOM element can simply be set directly, using widget:

// Foo is the component, e.g., Menu, Button, InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo( "widget" ).css( "height", "100px" );
$( ".selector" ).ojFoo( "widget" ).addClass( "my-class" );

A collection of settings impacting the launch of submenus.

This option affects submenus, while the similar openOptions affects the top-level menu.

Source:
Examples

Initialize the menu with the submenuOpenOptions option specified:

$( ".selector" ).ojMenu({ submenuOpenOptions: { 
    "position": { "my": "start top", "at": "end<5 top+5", "collision": "flipfit" } 
} });

Get or set the submenuOpenOptions option, after initialization:

// Get one
var value = $( ".selector" ).ojMenu( "option", "submenuOpenOptions.position" );

// Get all (currently only one)
var values = $( ".selector" ).ojMenu( "option", "submenuOpenOptions" );

// Set one
$( ".selector" ).ojMenu( "option", "submenuOpenOptions.position", { 
    "my": "start top", "at": "start bottom", "collision": "flipfit" 
} );

// Set many (currently only one)
$( ".selector" ).ojMenu( "option", "submenuOpenOptions", { 
    position: { "my": "start top", "at": "start bottom", "collision": "flipfit" } 
} );

Determines the position of submenus.

Please refer to the jQuery UI Position utility for details about the various choices. In addition to that syntax, note that JET supports the following reading direction-aware extended syntax in the my and at fields:

  • JET supports start and end values wherever left and right are supported. The start value means "left in LTR; right in RTL", values in the my and at fields wherever left and right are supported. The start value means "left in LTR; right in RTL", while the end value means "right in LTR; left in RTL."
  • Similarly, JET supports > and < operators wherever + and - are supported. The > value means "+ in LTR; - in RTL", while the < value means "- in LTR; + in RTL." E.g. a my value of "start>40" shifts the submenu 40px "endward," while a my value of "start<40" shifts the submenu 40px "startward."

By default, the submenu is positioned relative to the parent menu item, but if a value is set on the of field, then the submenu is positioned relative to that element or position instead.

Default Value:
  • { "my": "start top", "at": "end top", "collision": "flipfit" }
Source:
Examples

Initialize the menu with the submenuOpenOptions.position option specified:

$( ".selector" ).ojMenu({ openOptions: { 
    position: { "my": "start top", "at": "end<5 top+5", "collision": "flipfit" } 
} });

Get or set the submenuOpenOptions.position sub-option, after initialization:

// getter
var position = $( ".selector" ).ojMenu( "option", "submenuOpenOptions.position" );

// setter:
$( ".selector" ).ojMenu( "option", "submenuOpenOptions.position", { 
    "my": "start top", "at": "end<5 top+5", "collision": "flipfit" 
} );

translations :Object

A collection of translated resources from the translation bundle, or null if this component has no resources. Resources may be accessed and overridden individually or collectively, as seen in the examples.

If this component has (or inherits) translations, their documentation immediately follows this doc entry.

Default Value:
  • an object containing all resources relevant to the component and all its superclasses, or null if none
Inherited From:
Source:
Examples

Initialize the component, overriding some translated resources. This syntax leaves the other translations intact at create time, but not if called after create time:

// Foo is InputDate, InputNumber, etc.
$( ".selector" ).ojFoo({ "translations": { someKey: "someValue",
                                           someOtherKey: "someOtherValue" } });

Get or set the translations option, after initialization:

// Get one.  (Foo is InputDate, InputNumber, etc.)
var value = $( ".selector" ).ojFoo( "option", "translations.someResourceKey" );

// Get all.  (Foo is InputDate, InputNumber, etc.)
var values = $( ".selector" ).ojFoo( "option", "translations" );

// Set one, leaving the others intact.  (Foo is InputDate, InputNumber, etc.)
$( ".selector" ).ojFoo( "option", "translations.someResourceKey", "someValue" );

// Set many.  Any existing resource keys not listed are lost.  (Foo is InputDate, InputNumber, etc.)
$( ".selector" ).ojFoo( "option", "translations", { someKey: "someValue",
                                                    someOtherKey: "someOtherValue" } );

Events

beforeOpen

Triggered before this menu is launched via the open() method or via menu button or context menu functionality. The launch can be cancelled by calling event.preventDefault().

The ui.openOptions payload field contains the settings being used for this menu launch, resulting from merging the openOptions passed to open(), if any, with the openOptions component option.

This field is "live", meaning that the listener can alter fields such as position to affect this launch without affecting the component option. Since these changes are applied to the merged object, they supersede both the openOptions passed to open() and the openOptions component option.

If any of the above techniques are used to alter the built-in menu button or context menu functionality, it is the app's responsibility to ensure that the result is both correct and accessible.

Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
openOptions Object Settings in use for this menu launch.
Source:
Examples

Initialize the menu with the beforeOpen callback specified:

$( ".selector" ).ojMenu({
    "beforeOpen": function( event, ui ) {}
});

Bind an event listener to the ojbeforeopen event:

// $( ".selector" ) must select either the menu root, or the document, due to reparenting
$( ".selector" ).on( "ojbeforeopen", function( event, ui ) {
    // end-align the menu, without clobbering the other fields of openOptions or openOptions.position
    ui.openOptions.position.my = "end top";
    ui.openOptions.position.at = "end bottom";
    
    // change what is focused on menu dismissal
    ui.openOptions.launcher = "#myFocusableElement";
    
    // align the menu to something other than the launcher
    ui.openOptions.position.of = "#myElement";
} );

create

Triggered when the menu is created.
Properties:
Name Type Description
event Event jQuery event object
ui Object Currently empty
Source:
Examples

Initialize the menu with the create callback specified:

$( ".selector" ).ojMenu({
    "create": function( event, ui ) {}
});

Bind an event listener to the ojcreate event:

$( ".selector" ).on( "ojcreate", function( event, ui ) {} );

destroy

Triggered before the component is destroyed. This event cannot be canceled; the component will always be destroyed regardless.

Inherited From:
Source:
Examples

Initialize component with the destroy callback

// Foo is Button, InputText, etc.
$(".selector").ojFoo({
  'destroy': function (event, data) {}
});

Bind an event listener to the destroy event

$(".selector").on({
  'ojdestroy': function (event, data) {
      window.console.log("The DOM node id for the destroyed component is : %s", event.target.id);
  };
});

optionChange

Triggered when any option changes. The event payload has the following properties:

Properties:
Name Type Description
event Event jQuery event object
data Object event payload
Properties
Name Type Description
option string the name of the option that changed.
previousValue Object an Object holding the previous value of the option. When previousValue is not a primitive type, i.e., is an Object, it may hold the same value as the value property.
value Object an Object holding the current value of the option.
optionMetadata Object information about the option that changed
Properties
Name Type Description
writeback string "shouldWrite" or "shouldNotWrite". For use by the JET writeback mechanism; 'shouldWrite' indicates that the value should be written to the observable.
Inherited From:
Source:
Examples

Initialize component with the optionChange callback

// Foo is Button, InputText, etc.
$(".selector").ojFoo({
  'optionChange': function (event, data) {}
});

Bind an event listener to the ojoptionchange event

$(".selector").on({
  'ojoptionchange': function (event, data) {
      window.console.log("option that changed is: " + data['option']);
  };
});

select

Triggered when a menu item is selected. The only correct, supported way to react to the selection of a menu item is to listen for this event. Click listeners and href navigation should not be used.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item jQuery the selected menu item
Source:
Examples

Initialize the menu with the select callback specified:

$( ".selector" ).ojMenu({
    "select": function( event, ui ) {}
});

Bind an event listener to the ojselect event:

// $( ".selector" ) must select either the menu root, or the document, due to reparenting
$( ".selector" ).on( "ojselect", function( event, ui ) {} );

Methods

destroy()

Removes the menu functionality completely. This will return the element back to its pre-init state.

This method does not accept any arguments.

Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.
Example

Invoke the destroy method:

$( ".selector" ).ojMenu( "destroy" );

getNodeBySubId(locator) → {Element|null}

Returns the component DOM node indicated by the locator parameter.

If the locator or its subId is null, then this method returns the element on which this component was initialized.

If a subId was provided but no corresponding node can be located, then this method returns null. For more details on subIds, see the subIds section.

Parameters:
Name Type Description
locator Object An Object containing, at minimum, a subId property, whose value is a string that identifies a particular DOM node in this component.

If this component has (or inherits) any subIds, then they are documented in the "Sub-ID's" section of this document.

Subclasses of this component may support additional fields of the locator Object, to further specify the desired node.

Inherited From:
Source:
Returns:
The DOM node located by the subId string passed in locator, or null if none is found.
Type
Element | null
Example

Get the node for a certain subId:

// Foo is ojInputNumber, ojInputDate, etc.
var node = $( ".selector" ).ojFoo( "getNodeBySubId", {'subId': 'oj-some-sub-id'} );

open(event, openOptions, submenuOpenOptions)

Launches this menu as a popup, after firing the beforeOpen event. Listeners to that event can cancel the launch via event.preventDefault().

This method's optional openOptions and submenuOpenOptions params can be used to specify per-launch values for the settings in the corresponding component options, without altering those options. Those per-launch values can be further customized by a beforeOpen listener.

Parameters:
Name Type Argument Description
event jQuery.Event <optional>
What triggered the menu launch. May be null. May be omitted if subsequent params are omitted.
openOptions Object <optional>
Options to merge with the openOptions option. May be null. May be omitted if subsequent params are omitted.
submenuOpenOptions Object <optional>
Options to merge with the submenuOpenOptions option. May be null or omitted.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.
Example

Invoke the open method:

// override the launcher for this launch only, without affecting the other
// openOptions, and without affecting the component's openOptions option
$( ".selector" ).ojMenu( "open", myEvent, {launcher: "#myLauncher"} );

option(optionName, value) → {Object|undefined}

This method has several overloads, which get and set component options and their fields. The functionality is unchanged from that provided by JQUI. See the examples for details on each overload.

Parameters:
Name Type Argument Description
optionName string | Object <optional>
the option name (string, first two overloads), or the map (Object, last overload). Omitted in the third overload.
value Object <optional>
a value to set for the option. Second overload only.
Inherited From:
Source:
Returns:
The getter overloads return the retrieved value(s). When called via the public jQuery syntax, the setter overloads return the object on which they were called, to facilitate method chaining.
Type
Object | undefined
Examples

First overload: get one option:

This overload accepts a (possibly dot-separated) optionName param as a string, and returns the current value of that option.

var isDisabled = $( ".selector" ).ojFoo( "option", "disabled" ); // Foo is Button, Menu, etc.

// For object-valued options, dot notation can be used to get the value of a field or nested field.
var startIcon = $( ".selector" ).ojButton( "option", "icons.start" ); // icons is object with "start" field

Second overload: set one option:

This overload accepts two params: a (possibly dot-separated) optionName string, and a new value to which that option will be set.

$( ".selector" ).ojFoo( "option", "disabled", true ); // Foo is Button, Menu, etc.

// For object-valued options, dot notation can be used to set the value
// of a field or nested field, without altering the rest of the object.
$( ".selector" ).ojButton( "option", "icons.start", myStartIcon ); // icons is object with "start" field

Third overload: get all options:

This overload accepts no params, and returns a map of key/value pairs representing all the component options and their values.

var options = $( ".selector" ).ojFoo( "option" ); // Foo is Button, Menu, etc.

Fourth overload: set one or more options:

This overload accepts a single map of option-value pairs to set on the component. Unlike the first two overloads, dot notation cannot be used.

$( ".selector" ).ojFoo( "option", { disabled: true, bar: 42 } ); // Foo is Button, Menu, etc.

refresh()

Refreshes the visual state of the menu. JET components require a refresh() after the DOM is programmatically changed underneath the component. For Menu, this includes:
  • After menu items or submenus are added or removed.
  • After a change to a menu item's disabled status (which is set by applying or removing the oj-disabled class from the menu item).
  • After the reading direction (LTR vs. RTL) changes.

Once a submenu is added to the DOM, it is permanently associated with its parent menu item. The parent menu item can be moved or deleted, carrying its submenu with it in both cases, but the submenu should not be removed from the parent menu item, and the parent menu item's id should not be changed, even if there is a subsequent refresh().

Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.
Example

Invoke the refresh method:

$( ".selector" ).ojMenu( "refresh" );

widget() → {jQuery}

Returns a jQuery object containing the root element of the Menu component.
Source:
Returns:
the root element of the component
Type
jQuery
Example

Invoke the widget method:

var widget = $( ".selector" ).ojMenu( "widget" );

Non-public Methods

Note: Extending JET components is not currently supported. Thus, non-public methods are for internal use only.

<protected> _AfterCreate()

This method is called after _ComponentCreate, but before the create event is fired. The JET base component does tasks here that must happen after the component (subclass) has created itself in its override of _ComponentCreate. Notably, the base component handles the rootAttributes and contextMenu options here, since those options operate on the component root node, which for some components is created in their override of _ComponentCreate.

Subclasses should override this method only if they have tasks that must happen after a superclass's implementation of this method, e.g. tasks that must happen after the context menu is set on the component.

Overrides of this method should call this._super first.

Inherited From:
Source:

<protected> _AfterCreateEvent()

This method is called after the create event is fired. Components usually should not override this method, as it is rarely correct to wait until after the create event to perform a create-time task.

An example of a correct usage of this method is Dialog's auto-open behavior, which needs to happen after the create event.

Only behaviors (like Dialog auto-open behavior) should occur in this method. Component initialization must occur earlier, before the create event is fired, so that create listeners see a fully inited component.

Overrides of this method should call this._super first.

Do not confuse this method with the _AfterCreate method, which is more commonly used.

Inherited From:
Source:

<protected> _CompareOptionValues(option, value1, value2) → {boolean}

Compares 2 option values for equality and returns true if they are equal; false otherwise.

Parameters:
Name Type Description
option String the name of the option
value1 Object first value
value2 Object another value
Inherited From:
Source:
Returns:
Type
boolean

<protected> _ComponentCreate()

All component create-time initialization lives in this method, except the logic that specifically needs to live in _InitOptions, _AfterCreate, or _AfterCreateEvent, per the documentation for those methods. All DOM creation must happen here, since the intent of _AfterCreate, which is called next, is to contain superclass logic that must run after that DOM is created.

Overrides of this method should call this._super first.

Summary of create-time methods that components can override, in the order that they are called:

  1. _InitOptions
  2. _ComponentCreate (this method)
  3. _AfterCreate
  4. (The create event is fired here.)
  5. _AfterCreateEvent

For all of these methods, the contract is that overrides must call this._super first, so e.g., the _ComponentCreate entry means baseComponent._ComponentCreate, then _ComponentCreate in any intermediate subclasses, then _ComponentCreate in the leaf subclass.

Inherited From:
Source:

<protected> _create()

This method is final in JET. Components should instead override one or more of the overridable create-time methods listed in _ComponentCreate.

Inherited From:
Source:

<protected> _getCreateOptions()

This method is not used in JET. Components should instead override _InitOptions.

Inherited From:
Source:

<protected> _GetReadingDirection() → {string}

Determines whether the component is LTR or RTL.

Component responsibilities:

  • All components must determine directionality exclusively by calling this protected superclass method. (So that any future updates to the logic can be made in this one place.)
  • Components that need to know the directionality must call this method at create-time and from refresh(), and cache the value.
  • Components should not call this at other times, and should instead use the cached value. (This avoids constant DOM queries, and avoids any future issues with component reparenting (i.e. popups) if support for directional islands is added.)

App responsibilities:

  • The app specifies directionality by setting the HTML "dir" attribute on the <html> node. When omitted, the default is "ltr". (Per-component directionality / directional islands are not currently supported due to inadequate CSS support.)
  • As with any DOM change, the app must refresh() the component if the directionality changes dynamically. (This provides a hook for component housekeeping, and allows caching.)
Default Value:
  • "ltr"
Inherited From:
Source:
Returns:
the reading direction, either "ltr" or "rtl"
Type
string

<protected> _GetSavedAttributes(element) → {Object|null}

Gets the saved attributes for the provided element.

If you don't override _SaveAttributes and _RestoreAttributes, then this will return null.

If you override _SaveAttributes to call _SaveAllAttributes, then this will return all the attributes. If you override _SaveAttributes/_RestoreAttributes to do your own thing, then you may also have to override _GetSavedAttributes to return whatever you saved if you need access to the saved attributes.

Parameters:
Name Type Description
element Object jQuery selection, should be a single entry
Inherited From:
Source:
Returns:
savedAttributes - attributes that were saved for this element in _SaveAttributes, or null if none were saved.
Type
Object | null

<protected> _init()

JET components should almost never implement this JQUI method. Please consult an architect if you believe you have an exception. Reasons:

  • This method is called at create time, after the create event is fired. It is rare for that to be the appropriate time to perform a create-time task. For those rare cases, we have the _AfterCreateEvent method, which is preferred over this method since it is called only at that time, not also at re-init time (see next).
  • This method is also called at "re-init" time, i.e. when the initializer is called after the component has already been created. JET has not yet identified any desired semantics for re-initing a component.
Inherited From:
Source:

<protected> _InitOptions(originalDefaults, constructorOptions)

This method is called before _ComponentCreate, at which point the component has not yet been rendered. Component options should be initialized in this method, so that their final values are in place when _ComponentCreate is called.

This includes getting option values from the DOM, where applicable, and coercing option values (however derived) to their appropriate data type if needed.

No work other than setting options should be done in this method. In particular, nothing should be set on the DOM until _ComponentCreate, e.g. setting the disabled DOM attribute from the disabled option.

A given option (like disabled) appears in the constructorOptions param iff the app set it in the constructor:

  • If it appears in constructorOptions, it should win over what's in the DOM (e.g. disabled DOM attribute). If for some reason you need to tweak the value that the app set, then enable writeback when doing so: this.option('foo', bar, {'_context': {writeback: true, internalSet: true}}).
  • If it doesn't appear in constructorOptions, then that option definitely is not bound, so writeback is not needed. So if you need to set the option (e.g. from a DOM attribute), use this.option('foo', bar, {'_context': {internalSet: true}}).

Overrides of this method should call this._super first.

Parameters:
Name Type Argument Description
originalDefaults Object original default options defined on the component and its ancestors
constructorOptions Object <nullable>
options passed into the widget constructor
Inherited From:
Source:

<protected> _IsEffectivelyDisabled() → {boolean}

Determines whether this component is effectively disabled, i.e. it has its 'disabled' attribute set to true or it has been disabled by its ancestor component.

Inherited From:
Source:
Returns:
true if the component has been effectively disabled, false otherwise
Type
boolean

<protected> _NotifyAttached()

Notifies the component that its subtree has been connected to the document programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyContextMenuGesture(menu, event, eventType)

When the contextMenu option is set, this method is called when the user invokes the context menu via the default gestures: right-click, Press & Hold, and Shift-F10. Components should not call this method directly.

The default implementation simply calls this._OpenContextMenu(event, eventType). Overrides of this method should call that same method, perhaps with additional params, not menu.open().

This method may be overridden by components needing to do things like the following:

  • Customize the launcher or position passed to _OpenContextMenu(). See that method for guidance on these customizations.
  • Customize the menu contents. E.g. some components need to enable/disable built-in commands like Cut and Paste, based on state at launch time.
  • Bail out in some cases. E.g. components with UX approval to use PressHoldRelease rather than Press & Hold can override this method to say if (eventType !== "touch") this._OpenContextMenu(event, eventType);. When those components detect the alternate context menu gesture (e.g. PressHoldRelease), that separate listener should call this._OpenContextMenu(), not this method (_NotifyContextMenuGesture()), and not menu.open().

Components needing to do per-launch setup like the above tasks should do so in an override of this method, not in a beforeOpen listener or an _OpenContextMenu() override. This is discussed more fully here.

Parameters:
Name Type Description
menu Object The JET Menu to open as a context menu. Always non-null.
event Event What triggered the menu launch. Always non-null.
eventType string "mouse", "touch", or "keyboard". Never null.
Inherited From:
Source:

<protected> _NotifyDetached()

Notifies the component that its subtree has been removed from the document programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyHidden()

Notifies the component that its subtree has been made hidden programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyShown()

Notifies the component that its subtree has been made visible programmatically after the component has been created.

Inherited From:
Source:

<protected> _OpenContextMenu(event, eventType, openOptions, submenuOpenOptions, shallow)

The only correct way for a component to open its context menu is by calling this method, not by calling Menu.open() or _NotifyContextMenuGesture(). This method should be called in two cases:

  • This method is called by _NotifyContextMenuGesture() and its overrides. That method is called when the baseComponent detects the default context menu gestures: right-click, Press & Hold, and Shift-F10.
  • Components with UX-approved support for alternate context menu gestures like PressHoldRelease should call this method directly when those gestures are detected.

Components needing to customize how the context menu is launched, or do any per-launch setup, should do so in the caller of this method, (which is one of the two callers listed above), often by customizing the params passed to this method (_OpenContextMenu) per the guidance below. This setup should not be done in the following ways:

  • Components should not perform setup in a beforeOpen listener, as this can cause a race condition where behavior depends on who got their listener registered first: the component or the app. The only correct component use of a beforeOpen listener is when there's a need to detect whether something else launched the menu.
  • Components should not override this method (_OpenContextMenu), as this method is final. Instead, customize the params that are passed to it.

Guidance on setting OpenOptions fields:

Launcher:

Depending on individual component needs, any focusable element within the component can be the appropriate launcher for this launch.

Browser focus returns to the launcher on menu dismissal, so the launcher must at least be focusable. Typically a tabbable (not just focusable) element is safer, since it just focuses something the user could have focused on their own.

By default (i.e. if openOptions is not passed, or if it lacks a launcher field), the component init node is used as the launcher for this launch. If that is not focusable or is suboptimal for a given component, that component should pass something else. E.g. components with a "roving tabstop" (like Toolbar) should typically choose the current tabstop as their launcher.

The :focusable and :tabbable selectors may come in handy for choosing a launcher, e.g. something like this.widget().find(".my-class:tabbable").first().

Position:

By default, this method applies positioning that differs from Menu's default in the following ways: (The specific settings are subject to change.)

  • For mouse and touch events, the menu is positioned relative to the event, not the launcher.
  • For touch events, "my" is set to "start>40 center", to avoid having the context menu obscured by the user's finger.

Usually, if position needs to be customized at all, the only thing that needs changing is its "of" field, and only for keyboard launches (since mouse/touch launches should almost certainly keep the default "event" positioning). This situation arises anytime the element relative to which the menu should be positioned for keyboard launches is different than the launcher element (the element to which focus should be returned upon dismissal). For this case, { "position": {"of": eventType==="keyboard" ? someElement : "event"} } can be passed as the openOptions param.

Be careful not to clobber useful defaults by specifying too much. E.g. if you only want to customize "of", don't pass other fields like "my", since your value will be used for all modalities (mouse, touch, keyboard), replacing the modality-specific defaults that are usually correct. Likewise, don't forget the eventType==="keyboard" check if you only want to customize "of" for keyboard launches.

InitialFocus:

This method forces initialFocus to "menu" for this launch, so the caller needn't specify it.

Parameters:
Name Type Argument Description
event Event What triggered the context menu launch. Must be non-null.
eventType string "mouse", "touch", or "keyboard". Must be non-null. Passed explicitly since caller knows what it's listening for, and since events like contextmenu and click can be generated by various input modalities, making it potentially error-prone for this method to determine how they were generated.
openOptions Object <optional>
Options to merge with this method's defaults, which are discussed above. The result will be passed to Menu.open(). May be null or omitted. See also the shallow param.
submenuOpenOptions Object <optional>
Options to be passed through to Menu.open(). May be null or omitted.
shallow boolean <optional>
Whether to perform a deep or shallow merge of openOptions with this method's default value. The default and most commonly correct / useful value is false.
  • If true, a shallow merge is performed, meaning that the caller's position object, if passed, will completely replace this method's default position object.
  • If false or omitted, a deep merge is performed. For example, if the caller wishes to tweak position.of while keeping this method's defaults for position.my, position.at, etc., it can pass {"of": anOfValue} as the position value.

The shallow param is n/a for submenuOpenOptions, since this method doesn't apply any defaults to that. (It's a direct pass-through.)

Inherited From:
Source:

<protected> _RestoreAllAttributes()

Restores all the element's attributes which were saved in _SaveAllAttributes. This method is final in JET.

If a subclass wants to save/restore all attributes on create/destroy, then the subclass can override _SaveAttributes and call _SaveAllAttributes and also override _RestoreAttributes and call _RestoreAllAttributes.

Inherited From:
Source:

<protected> _RestoreAttributes()

Restore the attributes saved in _SaveAttributes.

_SaveAttributes is called during _create. And _RestoreAttributes is called during _destroy.

This base class default implementation does nothing.

We also have _SaveAllAttributes and _RestoreAllAttributes methods that save and restore all the attributes on an element. Component subclasses can opt into these _SaveAllAttributes/_RestoreAllAttributes implementations by overriding _SaveAttributes and _RestoreAttributes to call _SaveAllAttributes/_RestoreAllAttributes. If the subclass wants a different implementation (like save only the 'class' attribute), it can provide the implementation itself in _SaveAttributes/_GetSavedAttributes/_RestoreAttributes.

Inherited From:
Source:

<protected> _SaveAllAttributes(element)

Saves all the element's attributes within an internal variable. _RestoreAllAttributes will restore the attributes from this internal variable.

This method is final in JET. Subclasses can override _RestoreAttributes and call _RestoreAllAttributes.

The JSON variable will be held as:

[
  {
  "element" : element[i],
  "attributes" :
    {
      attributes[m]["name"] : {"attr": attributes[m]["value"], "prop": $(element[i]).prop(attributes[m]["name"])
    }
  }
]
Parameters:
Name Type Description
element Object jQuery selection to save attributes for
Inherited From:
Source:

<protected> _SaveAttributes(element)

Saves the element's attributes. This is called during _create. _RestoreAttributes will restore all these attributes and is called during _destroy.

This base class default implementation does nothing.

We also have _SaveAllAttributes and _RestoreAllAttributes methods that save and restore all the attributes on an element. Component subclasses can opt into these _SaveAllAttributes/_RestoreAllAttributes implementations by overriding _SaveAttributes and _RestoreAttributes to call _SaveAllAttributes/_RestoreAllAttributes. If the subclass wants a different implementation (like save only the 'class' attribute), it can provide the implementation itself in _SaveAttributes/_RestoreAttributes.

Parameters:
Name Type Description
element Object jQuery selection to save attributes for
Inherited From:
Source:

<protected> _SetRootAttributes()

Reads the rootAttributes option, and sets the root attributes on the component's root DOM element. See rootAttributes for the set of supported attributes and how they are handled.

Inherited From:
Source:
Throws:
if unsupported attributes are supplied.

<protected> _UnregisterChildNode()

Remove all listener references that were attached to the element which includes _activeable, _focusable and hoverable.
Inherited From:
Source: