Thursday, October 29, 2009

Javascript/Firefox: context menu popup


Note: This solution has some side-effects. A better one is provided in my another post here.

The context menu of Firefox behaves differently between the Windows and Linux platform. On Linux, the context menu pops up as soon as you press down the right button of the mouse; While on Windows, it shows after you press down and release the right button.

We can change the Linux style behavior by doing a little hack.

1. Capture the mousedown event and suppress the context menu.

1.1 Capture the mousedown event

addEventListener("mousedown", myMouseDown, true);

function myMouseDown(event)
{
   if (2 == event.button)
   {
      // Capture the pop-up event of the context menu.
      addEventListener("popupshowing", myNoContextMenu, true);
   }
}
1.2 Suppress the context menu

function myNoContextMenu(event)
{
   // Prevent the default action, i.e. popping up
   event.preventDefault();

   // Remove the event handler because we don't want to mess up the
   // popupshowing events triggered by others.
   removeEventListener("popupshowing", myNoContextMenu, true);
}
2. Capture the mouseup event and pop up the context menu.

1.1 Capture the mouseup event

addEventListener("mouseup", myMouseUp, true);

function myMouseUp(event)
{
   if (2 == event.button)
   {
      myShowContextMenu(event);
   }
}
1.2 Pop up the context menu

function myShowContextMenu(event)
{
   if (navigator.platform == "Win32")
      return;  // on Window context menu is already shown on mouseup.

   document.popupNode = event.originalTarget;
   var cm = document.getElementById("contentAreaContextMenu");
   cm.openPopupAtScreen(event.screenX, event.screenY, true);

   // Cancel the event.
   event.preventDefault();
   event.stopPropagation();
}

No comments:

 
Get This <