JavaScript simulate right click through code
Here is a more correct version if you do not care about where the context menu gets fired up
function fireContextMenu(el) {
var evt = el.ownerDocument.createEvent("HTMLEvents")
evt.initEvent('contextmenu', true, true) // bubbles = true, cancelable = true
if (document.createEventObject) {
return el.fireEvent('oncontextmenu', evt)
}
else {
return !el.dispatchEvent(evt)
}
}
If you do, we may have to use the previous one, fix up it's behaviour in IE, and populate the screenX, screenY, clientX, clientY etc appropriately
Just for good measure, here is a bit of doco on the parameters:
var myEvt = document.createEvent('MouseEvents');
myEvt.initMouseEvent(
'click' // event type
,true // can bubble?
,true // cancelable?
,window // the event's abstract view (should always be window)
,1 // mouse click count (or event "detail")
,100 // event's screen x coordinate
,200 // event's screen y coordinate
,100 // event's client x coordinate
,200 // event's client y coordinate
,false // whether or not CTRL was pressed during event
,false // whether or not ALT was pressed during event
,false // whether or not SHIFT was pressed during event
,false // whether or not the meta key was pressed during event
,1 // indicates which button (if any) caused the mouse event (1 = primary button)
,null // relatedTarget (only applicable for mouseover/mouseout events)
);
Great question!
I did some research, and it seems like you can fire a mouse event like is shown here, and make it a right-click by setting the button
or which
property to 2 (documented here).
Perhaps this code will work:
function rightClick(element){
var evt = element.ownerDocument.createEvent('MouseEvents');
var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE
evt.initMouseEvent('click', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, RIGHT_CLICK_BUTTON_CODE, null);
if (document.createEventObject){
// dispatch for IE
return element.fireEvent('onclick', evt)
}
else{
// dispatch for firefox + others
return !element.dispatchEvent(evt);
}
}
try this instead, reason what things didn't quite work is that the context menu is in fact bound to the oncontextmenu event.
function contextMenuClick(element){
var evt = element.ownerDocument.createEvent('MouseEvents');
var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE
evt.initMouseEvent('contextmenu', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, RIGHT_CLICK_BUTTON_CODE, null);
if (document.createEventObject){
// dispatch for IE
return element.fireEvent('onclick', evt)
}
else{
// dispatch for firefox + others
return !element.dispatchEvent(evt);
}
}