Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to simulate right click in javascript [duplicate]

Ok, so i know i can simulate a click by running this code

document.getElementById('recover').click();

the closest this i could find was cntextmenu so i tried

document.getElementById('recover').contextmenu();

however this does nothing

Is it possible to right click and element to bring up the contextual menu so i can click an item on that list ? and if so could someone point me in the correct direction to accomplish such a goal ?

I've done some searching but the only thing i have found is jquery javascript capturing of the event not actually triggering the event

like image 819
mcgrailm Avatar asked Jun 13 '13 16:06

mcgrailm


2 Answers

with jQuery

$('#recover').trigger({
    type: 'mousedown',
    which: 3
});

otherwise

var element = document.getElementById('recover');
var e = element.ownerDocument.createEvent('MouseEvents');

e.initMouseEvent('contextmenu', true, true,
     element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
     false, false, false,2, null);


return !element.dispatchEvent(e);
like image 196
Ben McCormick Avatar answered Sep 28 '22 02:09

Ben McCormick


Sure, you can use the jQuery trigger() functionality.

$('#recover').trigger({
    type: 'mousedown',
    which: 3
});

Depending on what you're doing, you may wish to trigger a mouse down and then a mouse up, which could go like this:

$('#recover').trigger({
    type: 'mousedown',
    which: 3
}).trigger({
    type: 'mouseup',
    which: 3
});

I'm not a big fan of chaining long commands like that, but whatever is most readable for your app is fine.

like image 33
Jordan Avatar answered Sep 28 '22 01:09

Jordan