views:

189

answers:

3

I have read http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed and http://stackoverflow.com/questions/2445613/how-can-i-check-if-key-is-pressed-during-click-event-with-jquery

However my question is if you can get the same key event for all browsers? Currently I know that Firefox gives the command button (Mac) the code 224 while Chrome and Safari give it the value 91. Is the best approach to simply check what browser the user is using and base the key pressed on that or is there a way so that I can get 1 key code across all browsers? Note I am getting the value with the:

var code = (evt.keyCode ? evt.keyCode : evt.which);

I would love to not use a plugin if possible just because I only need to know about the command/ctrl (windows system) key pressed.

+2  A: 

jQuery already handles that. To check if control was pressed you should use:

$(window).keydown(function (e){
    if (e.ctrlKey) alert("control");
});

The list of modifier keys:

e.ctrlKey
e.altKey
e.shiftKey

And as fudgey suggested:

e.metaKey

Might work on MAC. Some other ways here as well.

BrunoLM
I want it to be the commandkey if the OS is Mac however and ctrl if it is a Windows, so simply using the ctrlKey doesn't work.
Craig
@Craig, try using `if (e.metaKey || e.ctrlKey) {...}`
fudgey
A: 

I found this plugin on Ajaxian,

http://ajaxian.com/archives/cross-browser-keyboard-handler

Caimen
+1  A: 

If you're not interested in the the exact moment the Command key is pressed, just whether it is pressed when another key is pressed, then you can use the metaKey property of the event.

Otherwise, for keydown and keyup events, the property you need is keyCode in all browsers. Unfortunately, the Command key does not have the same key code in all browsers, and the left and right Commands have different values in WebKit (91 and 93 respectively). I can't see an easy way of detecting these keys without some kind of browser sniff, but there may be one. The which property definitely won't help you.

For more information, http://unixpapa.com/js/key.html has comprehensive coverage of key event handling in all the major browsers.

Tim Down
True, but he is using jQuery's [`keydown`](http://api.jquery.com/keydown/), which normalizes the key code in the `which` property of the Event interface.
Marcel Korpel
+1 for using `<kbd>` in your markup :)
Jason
@Jason: Heh. I saw it another answer and had been waiting for an excuse to use it :)
Tim Down