Skip to content Skip to sidebar Skip to footer

How To Simulate Right Click In Javascript

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.getElementB

Solution 1:

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

Solution 2:

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.

Post a Comment for "How To Simulate Right Click In Javascript"