How to create a right-click event in all browsers

Small context: The
application I'm working on has a right-click context menu for certain objects on the screen. The current design that each of these objects listens for for a right-click, sends an AJAX request to get the context data for this object, uses this data to create PopupMenu2 from Dojo 0.4.3 (I know!), And then creates a right-click. to launch the Dojo menu.

I am trying to figure out a way to generate a right-click event for all browsers. Currently, we support only IE and use the oncontextmenu event.

Limitations:

  • No jQuery :(
  • I cannot preload all the data for the objects on the screen in order to create a Dojo menu and avoid an AJAX request.
+3
source share
1 answer

This should start by creating a right-click event. The key to the right click is the button parameter: button = 2.

if (document.createEvent) {
  var rightClick = document.createEvent('MouseEvents');
  rightClick.initMouseEvent(
    'click', // type
    true,    // canBubble
    true,    // cancelable
    window,  // view - set to the window object
    1,       // detail - # of mouse clicks
    10,       // screenX - the page X coordinate
    10,       // screenY - the page Y coordinate
    10,       // clientX - the window X coordinate
    10,       // clientY - the window Y coordinate
    false,   // ctrlKey
    false,   // altKey
    false,   // shiftKey
    false,   // metaKey
    2,       // button - 1 = left, 2 = right
    null     // relatedTarget
  );
  document.dispatchEvent(rightClick);
} else if (document.createEventObject) { // for IE
  var rightClick = document.createEventObject();
  rightClick.type = 'click';
  rightClick.cancelBubble = true;
  rightClick.detail = 1;
  rightClick.screenX = 10;
  rightClick.screenY = 10;
  rightClick.clientX = 10;
  rightClick.clientY = 10;
  rightClick.ctrlKey = false;
  rightClick.altKey = false;
  rightClick.shiftKey = false;
  rightClick.metaKey = false;
  rightClick.button = 2;
  document.fireEvent('onclick', rightClick);
}

I would suggest Googleing for 'document.createEvent' and 'document.createEventObject' for more details on the API from Mozilla and MSDN.

Hope this helps!

+4
source

Source: https://habr.com/ru/post/1720306/


All Articles