Skip to content Skip to sidebar Skip to footer

How To Generate A Right-click Event In All Browsers

A little context: The app I'm working on has a right-click context menu for certain objects on the screen. The current design as that each of these objects listens for a right-clic

Solution 1:

This should get you started with generating 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', // typetrue,    // canBubbletrue,    // cancelablewindow,  // view - set to the window object1,       // detail - # of mouse clicks10,       // screenX - the page X coordinate10,       // screenY - the page Y coordinate10,       // clientX - the window X coordinate10,       // clientY - the window Y coordinatefalse,   // ctrlKeyfalse,   // altKeyfalse,   // shiftKeyfalse,   // metaKey2,       // button - 1 = left, 2 = rightnull// relatedTarget
  );
  document.dispatchEvent(rightClick);
} elseif (document.createEventObject) { // for IEvar 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 detail on the API from the Mozilla and MSDN sites.

Hope this helps!

Post a Comment for "How To Generate A Right-click Event In All Browsers"