18

I am trying to late-bind context menus to elements, using the ContextMenu plugin. So on the first right-click on those elements, I would like to :

  1. intercept the right-click through a live event on a certain "uncontextmenued" class,
  2. determine if the data('events').contextmenu exists,
  3. if not, attach the context-menu (and change the class to avoid re-throwing this live process),
  4. re-throw the right-click event to show the right-click.

I'm having trouble with the last item. jQuery allows to .click() or to .trigger('click'), which simulate a left-click, but there seems not to be a way to fire a right-click event through trigger.

Or is there?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
glmxndr
  • 45,516
  • 29
  • 93
  • 118

3 Answers3

31

You can trigger it by

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

http://api.jquery.com/trigger/#example-5

Niclas Sahlin
  • 1,125
  • 9
  • 15
  • 2
    Ok that put me on the right track. Just to complete the answer, the quoted plugin actually needs a mousedown followed by a mouseup... So triggering like Niclas said must be followed by a trigger('mouseup'). Since it's the 'button' property, and not the 'which' property which is read by the plugin, the actual answer to my problem was $('#element').trigger('mousedown',{button:2}).trigger('mouseup') . Thanks Niclas. – glmxndr Jun 06 '11 at 12:42
  • Hi subtenante, one million thanks, I was after just the same functionality and your answer really helped me a lot, but I think you have an error there, I had to change it to: $('#element').trigger({type:'mousedown',button:2}).trigger({type:'mouseup'}); to make it work. – Xose Lluis Sep 06 '11 at 15:48
  • The same in my case, "mouseup" instead of "mousedown". – humkins Jul 25 '13 at 04:48
  • 3
    This does not work for me. I also tried the solution Ben Lesh provided without success. ? – sfandler Oct 16 '15 at 19:33
9

There is a newer way to do this:

$('#element').triggerHandler('contextmenu');

Documentation can be found here.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232
  • 4
    For me the `'contextMenu'` didn't work. Instead, `'contextmenu'` worked properly. – lort Feb 11 '14 at 14:56
-2

Similar to this, but I'm not sure if you may be referring to jQuery UI data, but.

$('#element').mousedown(function(event) 
{
    if(event.which == 3)
    {
        if(typeof($(this).data('events')) === 'undefined')
        {
            $(this).data('events', { somedata: 'hello' });
        }
        else
        {
            // "re-throw" right click context menu
        }
    }
});
MacMac
  • 34,294
  • 55
  • 151
  • 222