LA_
LA_

Reputation: 20429

How to react on listitem double click and to add context menu for each listitem?

I have listbox element in my xul. listitem elements are added there dynamically.

How can I:

  1. react on double click on each listitem?
  2. implement context menu for each listitem?

During listitems creation, I know unique id (numeric) of each record added there. Ideally when double click function is called and when context menu item is chosen, I should get this id (and it shouldn't be visible to the user).

Upvotes: 1

Views: 976

Answers (1)

Wladimir Palant
Wladimir Palant

Reputation: 57681

Events bubble which means that you can register your event handler on the <listbox> element. event.target allows you to find the <listitem> element:

listbox.addEventListener("dblclick", function(event)
{
  var target = event.target;
  while (target && target.localName != "listitem")
    target = target.parentNode;
  if (!target)
    return;   // Event target isn't a list item

  alert(target.getAttribute("recordId"));
}, false);

This assumes that you've added recordId attributes to your list items before adding them to the list.

Things work similarly with context menus (you add a context="..." attribute to the <listbox>), with the difference that context menus are usually initialized in the menu's popupshowing event. The target of this event is the context menu itself so it doesn't help you find the list item. However, there is a menupopup.triggerNode() property (the modern alternative to the deprecated document.popupNode) that lets you do the job:

menu.addEventListener("popupshowing", function(event)
{
  var target = event.target.triggerNode;
  while (target && target.localName != "listitem")
    target = target.parentNode;
  if (!target)
    return event.preventDefault(); // Don't show context menu without a list item

  alert(target.getAttribute("recordId"));
}, false);

Upvotes: 2

Related Questions