19

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?

3 Answers 3

32

You can trigger it by

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

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

4
  • 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 6, 2011 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 6, 2011 at 15:48
  • The same in my case, "mouseup" instead of "mousedown".
    – humkins
    Jul 25, 2013 at 4:48
  • 3
    This does not work for me. I also tried the solution Ben Lesh provided without success. ?
    – sfandler
    Oct 16, 2015 at 19:33
10

There is a newer way to do this:

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

Documentation can be found here.

1
  • 4
    For me the 'contextMenu' didn't work. Instead, 'contextmenu' worked properly.
    – lort
    Feb 11, 2014 at 14:56
-1

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
        }
    }
});
1
  • Sorry, but I want to trigger a right-click event, not attach an event to it.
    – glmxndr
    Jun 6, 2011 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.