10

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

5
  • I'd say it's better to use a custom menu so you can have a much better control over it. Commented Jun 13, 2013 at 16:32
  • Is it a custom context menu or the browser's? Commented Jun 13, 2013 at 16:33
  • You can't open the default browser context menu. You can hijack that and make your own though. Commented Jun 13, 2013 at 16:35
  • the duplicate question that i somehow failed to find works for for me now i just have to figure out which element to click :) Commented Jun 13, 2013 at 16:46
  • This answer was good for me, but I wanted to simulate a click at the current mouse position. So where the code says 0,0,0,0, I replaced the last two 0's with the current mouse x/y position relative to the screen. Commented Aug 11, 2023 at 19:33

2 Answers 2

12

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

5 Comments

Excellent, a downvote for a working solution. Well done anonymous chap.
Why doesn't this demo work? jsbin.com/OjubeKU/1/edit
What makes you think it's not working, @andreaconsole? You don't have any logging to prove it to a human, but the computer is probably working fine. What did you expect it to do? Also, you should create a new question probably.
you are right, Jordan, I expected to see the context menu, but I found that this will not happen, even if I didn't understand exactly why...
This does not work. Can you remove it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.