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');
}