Trigger right click using pure Javascript
How can I manually trigger a right click using Javascript?
I can do this with jQuery but I can only use pure Javascript in this case.
Solution 1:
Create an event using the CustomEvent
constructor, or (when it is not supported), create an event using document.createEvent
with as argument the string "HTMLEvents" (because you're going to create a click
event). Then, use the initEvent
method to create a click
event.
Finally, use the dispatchEvent
method to fire the event. If you're using IE, the fireEvent
method has to be used instead.
If you want to trigger the rightclick event, contextmenu
, use the code below:
var element = document.getElementById('yourElement');
if (window.CustomEvent) {
element.dispatchEvent(new CustomEvent('contextmenu'));
} else if (document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent('contextmenu', true, false);
element.dispatchEvent(ev);
} else { // Internet Explorer
element.fireEvent('oncontextmenu');
}
Solution 2:
Another variant, this time using the MouseEvent API which is a bit more modern. In my case I actually send all three events mouseup/mousedown/contextmenu:
var element = document.getElementById("yourElement");
var ev1 = new MouseEvent("mousedown", {
bubbles: true,
cancelable: false,
view: window,
button: 2,
buttons: 2,
clientX: element.getBoundingClientRect().x,
clientY: element.getBoundingClientRect().y
});
element.dispatchEvent(ev1);
var ev2 = new MouseEvent("mouseup", {
bubbles: true,
cancelable: false,
view: window,
button: 2,
buttons: 0,
clientX: element.getBoundingClientRect().x,
clientY: element.getBoundingClientRect().y
});
element.dispatchEvent(ev2);
var ev3 = new MouseEvent("contextmenu", {
bubbles: true,
cancelable: false,
view: window,
button: 2,
buttons: 0,
clientX: element.getBoundingClientRect().x,
clientY: element.getBoundingClientRect().y
});
element.dispatchEvent(ev3);