How can I check if a key is pressed during the click event with jQuery?

I would like to catch a click event with jQuery and be able to tell if a key was pressed at the same time so I can fork within the callback function based on the keypress event.

For example:

$("button").click(function() {
    if([KEYPRESSED WHILE CLICKED]) {
        // Do something...
    } else {
        // Do something different...
    }
});

Is this possible at all or how can it be done if it is possible?


Solution 1:

You can easily detect the shift, alt and control keys from the event properties;

$("button").click(function(evt) {
  if (evt.ctrlKey)
    alert('Ctrl down');
  if (evt.altKey)
    alert('Alt down');
  // ...
});

See quirksmode for more properties. If you want to detect other keys, see cletus's answer.

Solution 2:

You need to separately track the key status using keydown() and keyup():

var ctrlPressed = false;
$(window).keydown(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = true;
  }
}).keyup(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = false;
  }
});

See the list of key codes. Now you can check that:

$("button").click(function() {
  if (ctrlPressed) {
    // do something
  } else {
    // do something else
  }
});

Solution 3:

I was able to use it with JavaScript alone

 <a  href="" onclick="return Show(event)"></a>

  function Show(event) {
            if (event.ctrlKey) { 
                 alert('Ctrl down');
            }
     }

Solution 4:

Without stealing @Arun Prasad's thunder, here is a pure JS snippet I rehashed to stop the default action, which would otherwise open a new window if CTL+click is pressed.

function Show(event) 
{
  if (event.ctrlKey) 
  {
    alert('Ctrl held down which clicked');
  } 
  else 
  {
    alert('Ctrl NOT pressed');
  }
  return false
}
<p>Hold down CTL on the link to get a different message</p>

<a href="" onclick="return Show(event)">click me</a>