views:

365

answers:

3

Hi,

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. for example:

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

Does anyone know if this is possible at all or how it can be done if it is possible?

+4  A: 

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
  }
});
cletus
+1  A: 

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.

kkyy
I don't see that property on the jQuery Event object: http://api.jquery.com/category/events/event-object/
cletus
Well, as the page says, "Most properties from the original event are copied over and normalized to the new event object." ctrlKey, altKey etc. are part of the ecmascript standard (see the first link on the aforementioned jquery api page), so (at least in decent browsers) the event object usually has also those properties set.
kkyy
A: 

Thanks everyone that was great and answered my question perfectly.

If you've found an acceptable answer please accept it (press the tick below the number and arrows on the left). You can delete this answer too. You can use the comment feature to leave comments on particular answers or the question.
cletus