jquerycontextmenukeypressright-click

How to differentiate between 'right click using mouse' AND 'context menu key press on physical keyboard'


How do I differentiate between right click using mouse and context menu key press on a physical keyboard?

Using this code I tried printing event in console

$('#'+inputId).bind('contextmenu', function(e) {
    console.log(e);
});

I grabbed some output for the above code-

For right click using the mouse it is-

  1. button: 2
  2. originalEvent: MouseEvent
  3. type: "contextmenu"
  4. which: 3

For context menu key press on the keyboard it is-

  1. button: 2
  2. originalEvent: MouseEvent
  3. type: "contextmenu"
  4. which: 3

I want to perform some action only when 'context menu key' is pressed on the physical keyboard. How do I achieve that?


Solution

  • This will help you to capture the difference: Working Demo http://jsfiddle.net/pPnME/1/

    I have tested this on Alienware - Chrome, when you will right click you will see the right click alert other wise on keyboard you will see keyboard alert.

    Please note: you can identify the click based on which property: http://api.jquery.com/event.which/

    For key or mouse events, this property indicates the specific key or button that was pressed.

    Also note there are few plugins available to get the shortcut but I would recommend stick to the basic and use the demo I have given if its only to capture both event separately rest demo is all your to play :)

    Code

    /*
      1 = Left   Mousebutton
      2 = Centre Mousebutton
      3 = Right  Mousebutton
    */
    $('input').mousedown(function(e) {
        if (e.which === 3) {
            alert('rightclick'); /* Right Mousebutton was clicked! */
        }
    });
    $('input').bind('contextmenu', function(e) {
        alert('keyboard yeah');
        //console.log(e);
    });​