This
menu
is very
cool
left click here
left or right click here

Single [context] menu for multiple elements

This page demonstrates a feature of DynarchMenu which allows one to configure the same context menu for multiple elements. That's right, with one function call.

The magic, again, is made through a special CSS class which is assigned to the LI element that defines the popup. Here we have set:

<li class="context-class-div-hotspot">

And all div elements having the class "hotspot" will automagically be assigned a context menu. Please note that you also need to specify the tag name; if you want to have context menus on something else than DIV-s, say SPAN-s, then your class name will be: “context-class-span-hotspot” and all SPAN-s having the class “hotspot” will gain a context menu.

Because it's only one context menu for multiple elements, we need to use a special API in order to detect which element is the context menu for. The function defined in this page is called “ourActionHandler” and has the following definition:

function ourActionHandler(action) {
  var item = action.info;
  var triggerElement = item.menu.target;
  alert("\"" + item.label + "\" clicked on the element having innerHTML:\n\"" + triggerElement.innerHTML + "\"");
};

and we define menu items like this:

<a href="javascript:ourActionHandler(this);">Foo Bar item 1</a>

“this”, in this context, has a special meaning; it doesn't pass a reference to the link element as one JS coder might think. It will pass an internal object (the DynarchMenu action handler). Normally you shouldn't need to mess too much with this object; all it's needed is the following:

var item = action.info;

This gets a reference to the clicked menu item. Again, this is an internal object. We can get it's label by using:

var label = item.label;

Based on the label, we know what item has been clicked so we can setup an unique handler.

The source element (element whose context menu triggered the action) is retrieved like this:

var triggerElement = item.menu.target;